:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement ashby import source (#61653)
Tom Owers7c3b3725e4ad
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex d1f486bba577..537d09c2eb5e 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -46,6 +46,7 @@ the row lists both.| ---------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- || aircall | HTTP | requests | ✅ || asana | HTTP | requests | ✅ |+| ashby | HTTP | requests | ✅ || attio | HTTP | requests + `rest_source.RESTClient` | ✅ || bamboohr | HTTP | requests | ✅ || bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |@@ -175,7 +176,6 @@ doesn't conflict with concurrent PRs.- amplitude- apple_search_ads- appsflyer-- ashby- auth0- azure_blob- bigcommercediff --git a/posthog/temporal/data_imports/sources/ashby/ashby.py b/posthog/temporal/data_imports/sources/ashby/ashby.pynew file mode 100644index 000000000000..b93c42cec012--- /dev/null+++ b/posthog/temporal/data_imports/sources/ashby/ashby.py@@ -0,0 +1,203 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.ashby.settings import ASHBY_ENDPOINTS+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++ASHBY_BASE_URL = "https://api.ashbyhq.com"+PAGE_SIZE = 100 # Ashby's documented max (and default).+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint to confirm a key is genuine when no specific schema is being validated.+DEFAULT_PROBE_PATH = "department.list"++AUTH_ERROR_HINT = "Ashby API authentication or permission error"+++class AshbyRetryableError(Exception):+ pass+++class AshbyAPIError(Exception):+ pass+++class AshbyResumeConfig:+ cursor: str+++def _auth(api_key: str) -> tuple[str, str]:+ # Ashby uses HTTP Basic auth: API key as username, empty password.+ return (api_key, "")+++def _headers() -> dict[str, str]:+ return {"Content-Type": "application/json", "Accept": "application/json"}+++def _classify_failure_message(errors: list[Any]) -> tuple[bool, str]:+ """Return ``(is_auth_related, joined_message)`` for an ``success: false`` payload.++ Ashby reports many failures as HTTP 200 with ``success: false`` and an ``errors`` array,+ so we sniff the messages to decide whether it's an unrecoverable auth/permission problem.+ """+ message = "; ".join(str(e) for e in errors) or "unknown error"+ lowered = message.lower()+ is_auth = any(+ hint in lowered+ for hint in ("unauthorized", "not authorized", "invalid api key", "permission", "forbidden", "authentication")+ )+ return is_auth, message+++def _errors_from_payload(data: dict[str, Any]) -> list[Any]:+ errors = data.get("errors")+ if errors:+ return errors if isinstance(errors, list) else [errors]+ if data.get("error"):+ return [data["error"]]+ return []+++@retry(+ retry=retry_if_exception_type((AshbyRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ api_key: str,+ path: str,+ body: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.post(+ f"{ASHBY_BASE_URL}/{path}", json=body, auth=_auth(api_key), headers=_headers(), timeout=REQUEST_TIMEOUT_SECONDS+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise AshbyRetryableError(f"Ashby API error (retryable): status={response.status_code}, path={path}")++ if response.status_code in (401, 403):+ raise AshbyAPIError(f"{response.status_code} Client Error: {AUTH_ERROR_HINT} for path {path}")++ if not response.ok:+ logger.error(f"Ashby API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ if not data.get("success", False):+ is_auth, message = _classify_failure_message(_errors_from_payload(data))+ if is_auth:+ raise AshbyAPIError(f"{AUTH_ERROR_HINT} for path {path}: {message}")+ raise AshbyAPIError(f"Ashby API error for path {path}: {message}")++ return data+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AshbyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = ASHBY_ENDPOINTS[endpoint]+ session = make_tracked_session()++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor: Optional[str] = resume.cursor if resume else None+ if cursor:+ logger.debug(f"Ashby: resuming {endpoint} from cursor")++ while True:+ body: dict[str, Any] = {"limit": PAGE_SIZE}+ if cursor:+ body["cursor"] = cursor++ data = _fetch_page(session, api_key, config.path, body, logger)++ results = data.get("results") or []+ if results:+ yield results++ next_cursor = data.get("nextCursor")+ if not data.get("moreDataAvailable", False) or not next_cursor:+ break++ cursor = next_cursor+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages+ # are persisted); merge/replace dedupes on the primary key.+ resumable_source_manager.save_state(AshbyResumeConfig(cursor=cursor))+++def ashby_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AshbyResumeConfig],+) -> SourceResponse:+ config = ASHBY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_key,+ 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,+ )+++def check_access(api_key: str, path: str) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate credentials.++ Returns a normalized ``(status, message)`` where status mimics HTTP semantics even when+ Ashby reports the failure as HTTP 200 + ``success: false``:+ 200 = reachable, 401 = bad key, 403 = valid key without scope, other = unexpected.+ """+ session = make_tracked_session()+ try:+ response = session.post(+ f"{ASHBY_BASE_URL}/{path}", json={"limit": 1}, auth=_auth(api_key), headers=_headers(), timeout=15+ )+ except Exception as e:+ return 0, f"Could not connect to Ashby: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Ashby returned HTTP {response.status_code}"++ try:+ data = response.json()+ except ValueError:+ # A 200 that isn't JSON (e.g. a proxy/maintenance HTML page) is not a valid Ashby+ # response — fail validation rather than reporting the credentials as good.+ return 0, "Ashby returned a non-JSON response"++ if data.get("success", False):+ return 200, None++ is_auth, message = _classify_failure_message(_errors_from_payload(data))+ if is_auth:+ # Can't distinguish bad-key from missing-scope purely from the message; treat as 403+ # (valid key, insufficient scope) so source-create accepts keys scoped to a subset of+ # endpoints. A genuinely invalid key surfaces as HTTP 401 above.+ return 403, message+ return 400, messagediff --git a/posthog/temporal/data_imports/sources/ashby/settings.py b/posthog/temporal/data_imports/sources/ashby/settings.pynew file mode 100644index 000000000000..229b02cce6b7--- /dev/null+++ b/posthog/temporal/data_imports/sources/ashby/settings.py@@ -0,0 +1,52 @@+from dataclasses import dataclass+from typing import Optional+++@dataclass+class AshbyEndpointConfig:+ name: str+ """Table name we expose to the user (snake_case)."""+ path: str+ """Ashby RPC method, e.g. ``candidate.list`` (called as POST ``/<path>``)."""+ primary_key: list[str]+ partition_key: Optional[str] = None+ """A STABLE creation-time field to partition on. ``None`` disables partitioning.++ Only set where the object is documented to carry a top-level ``createdAt`` — never a+ mutable field like ``updatedAt`` (partitions would rewrite on every sync).+ """+++# Every Ashby object exposes a top-level ``id``, so the primary key is ``["id"]`` throughout.+#+# Incremental sync is intentionally not advertised: Ashby's only incremental mechanisms are an+# opaque ``syncToken`` (which does not map onto PostHog's timestamp-watermark model) and a+# ``createdAfter`` filter whose list endpoints provide no documented ordering guarantee — a+# watermark-based sync could silently skip rows. We ship full refresh; see source.py / the PR+# for the syncToken follow-up.+ASHBY_ENDPOINTS: dict[str, AshbyEndpointConfig] = {+ "candidates": AshbyEndpointConfig(+ name="candidates", path="candidate.list", primary_key=["id"], partition_key="createdAt"+ ),+ "applications": AshbyEndpointConfig(+ name="applications", path="application.list", primary_key=["id"], partition_key="createdAt"+ ),+ "jobs": AshbyEndpointConfig(name="jobs", path="job.list", primary_key=["id"], partition_key="createdAt"),+ "job_postings": AshbyEndpointConfig(name="job_postings", path="jobPosting.list", primary_key=["id"]),+ "offers": AshbyEndpointConfig(name="offers", path="offer.list", primary_key=["id"]),+ "interviews": AshbyEndpointConfig(name="interviews", path="interview.list", primary_key=["id"]),+ "interview_schedules": AshbyEndpointConfig(+ name="interview_schedules", path="interviewSchedule.list", primary_key=["id"]+ ),+ "users": AshbyEndpointConfig(name="users", path="user.list", primary_key=["id"]),+ "departments": AshbyEndpointConfig(name="departments", path="department.list", primary_key=["id"]),+ "locations": AshbyEndpointConfig(name="locations", path="location.list", primary_key=["id"]),+ "sources": AshbyEndpointConfig(name="sources", path="source.list", primary_key=["id"]),+ "archive_reasons": AshbyEndpointConfig(name="archive_reasons", path="archiveReason.list", primary_key=["id"]),+ "candidate_tags": AshbyEndpointConfig(name="candidate_tags", path="candidateTag.list", primary_key=["id"]),+ "custom_fields": AshbyEndpointConfig(name="custom_fields", path="customField.list", primary_key=["id"]),+ "openings": AshbyEndpointConfig(name="openings", path="opening.list", primary_key=["id"]),+ "projects": AshbyEndpointConfig(name="projects", path="project.list", primary_key=["id"]),+}++ENDPOINTS = tuple(ASHBY_ENDPOINTS.keys())diff --git a/posthog/temporal/data_imports/sources/ashby/source.py b/posthog/temporal/data_imports/sources/ashby/source.pyindex eeb48c5dab93..6b3c2c3f1964 100644--- a/posthog/temporal/data_imports/sources/ashby/source.py+++ b/posthog/temporal/data_imports/sources/ashby/source.py@@ -2,22 +2,32 @@ from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.sources.ashby.ashby import (+ AUTH_ERROR_HINT,+ DEFAULT_PROBE_PATH,+ AshbyResumeConfig,+ ashby_source,+ check_access,+)+from posthog.temporal.data_imports.sources.ashby.settings import ASHBY_ENDPOINTS, ENDPOINTS+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import AshbySourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType-# TODO(Andrew J. McGehee): implement the source logic for AshbySource-@SourceRegistry.register-class AshbySource(SimpleSource[AshbySourceConfig]):+class AshbySource(ResumableSource[AshbySourceConfig, AshbyResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ASHBY@@ -26,21 +36,30 @@ class AshbySource(SimpleSource[AshbySourceConfig]):def get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.ASHBY,- iconPath="/static/services/ashby.png",- label="Ashby", # only needed if the readable name is complex. delete otherwise- caption=None, # only needed if you want to inline docs- docsUrl=None, # TODO(Andrew J. McGehee): link to the docs in the website, full path including https://- fields=cast(list[FieldType], []), # TODO(Andrew J. McGehee): add source config fields here+ label="Ashby",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,- )+ caption="""Enter your Ashby API key to pull your Ashby (ATS) data into the PostHog Data warehouse.- def validate_credentials(- self, config: AshbySourceConfig, team_id: int, schema_name: Optional[str] = None- ) -> tuple[bool, str | None]:- # TODO(Andrew J. McGehee): implement the logic to validate the credentials of your source,- # e.g. check the validity of API keys. returns a tuple of whether the credentials are valid,- # and if not, returns an error message to return to the user- raise NotImplementedError()+You can create an API key under **Admin → API Keys** in Ashby. Grant read permissions for the data you want to sync, for example:+- `candidatesRead`, `applicationsRead`, `jobsRead`, `offersRead`, `interviewsRead`, `usersRead`+""",+ iconPath="/static/services/ashby.png",+ docsUrl="https://posthog.com/docs/cdp/sources/ashby",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )def get_schemas(self,@@ -50,7 +69,64 @@ class AshbySource(SimpleSource[AshbySourceConfig]):names: list[str] | None = None,force_refresh: bool = False,) -> list[SourceSchema]:- raise NotImplementedError()+ # Ashby exposes incremental sync only via an opaque syncToken and an unordered+ # `createdAfter` filter — neither maps safely onto PostHog's timestamp-watermark+ # model — so every endpoint is full refresh for now.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas- def source_for_pipeline(self, config: AshbySourceConfig, inputs: SourceInputs) -> SourceResponse:- raise NotImplementedError()+ def validate_credentials(+ self, config: AshbySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if schema_name is not None and schema_name not in ASHBY_ENDPOINTS:+ return False, f"Unknown Ashby schema '{schema_name}'"++ path = ASHBY_ENDPOINTS[schema_name].path if schema_name is not None else DEFAULT_PROBE_PATH+ status, message = check_access(config.api_key, path)++ if status == 200:+ return True, None+ if status == 401:+ return False, "Invalid Ashby API key"+ if status == 403:+ # Valid key without scope for this endpoint. Accept at source-create (the user may+ # only intend to sync a subset); reject when validating a specific schema.+ if schema_name is not None:+ return False, f"Your Ashby API key does not have permission to read '{schema_name}'"+ return True, None++ return False, message or "Could not validate Ashby credentials"++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Ashby API key is invalid or expired. Please generate a new key and reconnect.",+ "403 Client Error": "Your Ashby API key does not have the required permissions. Please check the key's scopes and try again.",+ AUTH_ERROR_HINT: "Your Ashby API key is invalid or lacks the required permissions. Please check the key and try again.",+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AshbyResumeConfig]:+ return ResumableSourceManager[AshbyResumeConfig](inputs, AshbyResumeConfig)++ def source_for_pipeline(+ self,+ config: AshbySourceConfig,+ resumable_source_manager: ResumableSourceManager[AshbyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return ashby_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )diff --git a/posthog/temporal/data_imports/sources/ashby/tests/test_ashby.py b/posthog/temporal/data_imports/sources/ashby/tests/test_ashby.pynew file mode 100644index 000000000000..f045073483ba--- /dev/null+++ b/posthog/temporal/data_imports/sources/ashby/tests/test_ashby.py@@ -0,0 +1,215 @@+from typing import Any, Optional++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.ashby.ashby import (+ ASHBY_BASE_URL,+ AUTH_ERROR_HINT,+ AshbyAPIError,+ AshbyResumeConfig,+ _classify_failure_message,+ _errors_from_payload,+ ashby_source,+ check_access,+ get_rows,+)+from posthog.temporal.data_imports.sources.ashby.settings import ENDPOINTS++SESSION_PATH = "posthog.temporal.data_imports.sources.ashby.ashby.make_tracked_session"+++class FakeResponse:+ def __init__(+ self, status_code: int = 200, json_data: Optional[dict[str, Any]] = None, raise_json: bool = False+ ) -> None:+ self.status_code = status_code+ self._json = json_data if json_data is not None else {}+ self.text = str(self._json)+ self._raise_json = raise_json++ @property+ def ok(self) -> bool:+ return 200 <= self.status_code < 300++ def json(self) -> dict[str, Any]:+ if self._raise_json:+ raise ValueError("no json")+ return self._json++ def raise_for_status(self) -> None:+ if not self.ok:+ raise Exception(f"{self.status_code} Client Error")+++class FakeSession:+ def __init__(self, responses: list[FakeResponse]) -> None:+ self._responses = list(responses)+ self.calls: list[dict[str, Any]] = []++ def post(self, url: str, json: Any = None, auth: Any = None, headers: Any = None, timeout: Any = None):+ self.calls.append({"url": url, "json": json, "auth": auth, "headers": headers})+ return self._responses[0] if len(self._responses) == 1 else self._responses.pop(0)+++def _manager(can_resume: bool = False, state: Optional[AshbyResumeConfig] = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = can_resume+ manager.load_state.return_value = state+ return manager+++class TestClassifyFailureMessage:+ @pytest.mark.parametrize(+ "errors, expected_auth",+ [+ (["Invalid API key"], True),+ (["You are not authorized to perform this action"], True),+ (["Missing permission: candidatesRead"], True),+ (["Forbidden"], True),+ (["sync_token_expired"], False),+ (["Some random validation error"], False),+ ([], False),+ ],+ )+ def test_classify(self, errors: list[str], expected_auth: bool) -> None:+ is_auth, message = _classify_failure_message(errors)+ assert is_auth is expected_auth+ assert isinstance(message, str)+++class TestErrorsFromPayload:+ @pytest.mark.parametrize(+ "payload, expected",+ [+ ({"errors": ["a", "b"]}, ["a", "b"]),+ ({"errors": "single"}, ["single"]),+ ({"error": "legacy"}, ["legacy"]),+ ({"success": False}, []),+ ],+ )+ def test_errors_from_payload(self, payload: dict[str, Any], expected: list[Any]) -> None:+ assert _errors_from_payload(payload) == expected+++class TestGetRows:+ def test_paginates_until_no_more_data(self) -> None:+ responses = [+ FakeResponse(+ json_data={"success": True, "results": [{"id": "1"}], "moreDataAvailable": True, "nextCursor": "c1"}+ ),+ FakeResponse(json_data={"success": True, "results": [{"id": "2"}], "moreDataAvailable": False}),+ ]+ session = FakeSession(responses)+ manager = _manager()++ with mock.patch(SESSION_PATH, return_value=session):+ batches = list(get_rows("dummy-key", "candidates", mock.MagicMock(), manager))++ assert batches == [[{"id": "1"}], [{"id": "2"}]]+ # First call has no cursor, second forwards nextCursor.+ assert "cursor" not in session.calls[0]["json"]+ assert session.calls[1]["json"]["cursor"] == "c1"+ assert session.calls[0]["json"]["limit"] == 100+ assert session.calls[0]["auth"] == ("dummy-key", "")+ assert session.calls[0]["url"] == f"{ASHBY_BASE_URL}/candidate.list"++ def test_saves_state_after_yielding_each_page(self) -> None:+ responses = [+ FakeResponse(+ json_data={"success": True, "results": [{"id": "1"}], "moreDataAvailable": True, "nextCursor": "c1"}+ ),+ FakeResponse(json_data={"success": True, "results": [{"id": "2"}], "moreDataAvailable": False}),+ ]+ manager = _manager()++ with mock.patch(SESSION_PATH, return_value=FakeSession(responses)):+ list(get_rows("k", "candidates", mock.MagicMock(), manager))++ manager.save_state.assert_called_once_with(AshbyResumeConfig(cursor="c1"))++ def test_resumes_from_saved_cursor(self) -> None:+ responses = [FakeResponse(json_data={"success": True, "results": [{"id": "9"}], "moreDataAvailable": False})]+ session = FakeSession(responses)+ manager = _manager(can_resume=True, state=AshbyResumeConfig(cursor="resume-cursor"))++ with mock.patch(SESSION_PATH, return_value=session):+ batches = list(get_rows("k", "candidates", mock.MagicMock(), manager))++ assert batches == [[{"id": "9"}]]+ assert session.calls[0]["json"]["cursor"] == "resume-cursor"++ def test_empty_results_yield_nothing(self) -> None:+ responses = [FakeResponse(json_data={"success": True, "results": [], "moreDataAvailable": False})]++ with mock.patch(SESSION_PATH, return_value=FakeSession(responses)):+ batches = list(get_rows("k", "users", mock.MagicMock(), _manager()))++ assert batches == []++ @pytest.mark.parametrize(+ "response",+ [+ FakeResponse(status_code=401),+ FakeResponse(status_code=403),+ ],+ )+ def test_http_auth_errors_raise_matchable_api_error(self, response: FakeResponse) -> None:+ with mock.patch(SESSION_PATH, return_value=FakeSession([response])):+ with pytest.raises(AshbyAPIError) as exc:+ list(get_rows("k", "candidates", mock.MagicMock(), _manager()))+ assert f"{response.status_code} Client Error" in str(exc.value)++ def test_success_false_auth_error_raises_matchable_api_error(self) -> None:+ response = FakeResponse(json_data={"success": False, "errors": ["Missing permission: candidatesRead"]})+ with mock.patch(SESSION_PATH, return_value=FakeSession([response])):+ with pytest.raises(AshbyAPIError) as exc:+ list(get_rows("k", "candidates", mock.MagicMock(), _manager()))+ assert AUTH_ERROR_HINT in str(exc.value)+++class TestCheckAccess:+ @pytest.mark.parametrize(+ "response, expected_status",+ [+ (FakeResponse(json_data={"success": True, "results": []}), 200),+ (FakeResponse(status_code=401), 401),+ (FakeResponse(status_code=403), 403),+ (FakeResponse(json_data={"success": False, "errors": ["Missing permission"]}), 403),+ (FakeResponse(json_data={"success": False, "errors": ["bad request"]}), 400),+ (FakeResponse(status_code=500), 500),+ (FakeResponse(raise_json=True), 0),+ ],+ )+ def test_status_mapping(self, response: FakeResponse, expected_status: int) -> None:+ with mock.patch(SESSION_PATH, return_value=FakeSession([response])):+ status, _message = check_access("k", "department.list")+ assert status == expected_status++ def test_connection_error_returns_zero(self) -> None:+ session = mock.MagicMock()+ session.post.side_effect = Exception("boom")+ with mock.patch(SESSION_PATH, return_value=session):+ status, message = check_access("k", "department.list")+ assert status == 0+ assert message is not None+++class TestAshbySource:+ def test_candidates_partitioned_by_created_at(self) -> None:+ response = ashby_source("k", "candidates", mock.MagicMock(), _manager())+ assert response.name == "candidates"+ assert response.primary_keys == ["id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["createdAt"]++ def test_reference_endpoint_is_unpartitioned(self) -> None:+ response = ashby_source("k", "users", mock.MagicMock(), _manager())+ assert response.partition_mode is None+ assert response.partition_keys is None+ assert response.primary_keys == ["id"]++ def test_all_endpoints_buildable(self) -> None:+ for endpoint in ENDPOINTS:+ response = ashby_source("k", endpoint, mock.MagicMock(), _manager())+ assert response.primary_keys == ["id"]diff --git a/posthog/temporal/data_imports/sources/ashby/tests/test_ashby_source.py b/posthog/temporal/data_imports/sources/ashby/tests/test_ashby_source.pynew file mode 100644index 000000000000..42da4397e14c--- /dev/null+++ b/posthog/temporal/data_imports/sources/ashby/tests/test_ashby_source.py@@ -0,0 +1,143 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.ashby.ashby import AshbyResumeConfig+from posthog.temporal.data_imports.sources.ashby.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.ashby.source import AshbySource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import AshbySourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestAshbySource:+ def setup_method(self) -> None:+ self.source = AshbySource()+ self.team_id = 123+ self.config = AshbySourceConfig(api_key="ashby-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.ASHBY++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Ashby"+ assert config.label == "Ashby"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/ashby.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # Ashby has no timestamp-watermark incremental, so every schema is full refresh.+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["candidates"])+ assert len(schemas) == 1+ assert schemas[0].name == "candidates"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Ashby API authentication or permission error for path candidate.list",+ "403 Client Error: Ashby API authentication or permission error for path job.list",+ "Ashby API authentication or permission error for path candidate.list: Missing permission",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @pytest.mark.parametrize(+ "unrelated_error",+ [+ "500 Server Error for path candidate.list",+ "Ashby API error for path candidate.list: validation failed",+ ],+ )+ def test_non_retryable_errors_ignore_unrelated(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @pytest.mark.parametrize(+ "status, schema_name, expected_valid, expected_message",+ [+ (200, None, True, None),+ (401, None, False, "Invalid Ashby API key"),+ # 403 at source-create is accepted (key may be scoped to a subset of endpoints).+ (403, None, True, None),+ # 403 for a specific schema is rejected.+ (403, "candidates", False, "Your Ashby API key does not have permission to read 'candidates'"),+ (400, None, False, "boom"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.ashby.source.check_access")+ def test_validate_credentials(+ self,+ mock_check: mock.MagicMock,+ status: int,+ schema_name: str | None,+ expected_valid: bool,+ expected_message: str | None,+ ) -> None:+ mock_check.return_value = (status, "boom")+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)+ assert is_valid is expected_valid+ assert message == expected_message++ @mock.patch("posthog.temporal.data_imports.sources.ashby.source.check_access")+ def test_validate_credentials_probes_schema_path_when_given(self, mock_check: mock.MagicMock) -> None:+ mock_check.return_value = (200, None)+ self.source.validate_credentials(self.config, self.team_id, schema_name="candidates")+ mock_check.assert_called_once_with("ashby-key", "candidate.list")++ @mock.patch("posthog.temporal.data_imports.sources.ashby.source.check_access")+ def test_validate_credentials_uses_default_probe_without_schema(self, mock_check: mock.MagicMock) -> None:+ mock_check.return_value = (200, None)+ self.source.validate_credentials(self.config, self.team_id)+ mock_check.assert_called_once_with("ashby-key", "department.list")++ @mock.patch("posthog.temporal.data_imports.sources.ashby.source.check_access")+ def test_validate_credentials_rejects_unknown_schema_without_probing(self, mock_check: mock.MagicMock) -> None:+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name="not_a_table")+ assert is_valid is False+ assert message == "Unknown Ashby schema 'not_a_table'"+ mock_check.assert_not_called()++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is AshbyResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.ashby.source.ashby_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_ashby_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "candidates"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_ashby_source.assert_called_once()+ kwargs = mock_ashby_source.call_args.kwargs+ assert kwargs["api_key"] == "ashby-key"+ assert kwargs["endpoint"] == "candidates"+ assert kwargs["resumable_source_manager"] is managerdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 848eebe943fd..326ccc701cde 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -148,7 +148,7 @@ class AsanaSourceConfig(config.Config):@config.configclass AshbySourceConfig(config.Config):- pass+ api_key: str@config.config