: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 justsift import source (#68564)
Tom Owers066d4bb2b6f7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 9ea8f40ad51f..80cc586911a8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -202,6 +202,7 @@ the row lists both.| jobnimbus | HTTP | requests | ✅ || jotform | HTTP | requests | ✅ || justcall | HTTP | requests | ✅ |+| justsift | HTTP | requests | ✅ || k6_cloud | HTTP | requests | ✅ || katana | HTTP | requests | ✅ || klaviyo | HTTP | requests | ✅ |@@ -515,7 +516,6 @@ doesn't conflict with concurrent PRs.- jamf_pro- jobber- judgeme_reviews-- justsift- kafka- keka- kisidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex cc41d3b3eb90..df933356148c 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@@ -1721,7 +1721,7 @@ class JustCallSourceConfig(config.Config):@config.configclass JustSiftSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/canonical_descriptions.pynew file mode 100644index 000000000000..cbc01207cf5d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/canonical_descriptions.py@@ -0,0 +1,37 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Sift (JustSift) API docs (https://developers.justsift.com).+# Person profiles are largely dynamic (custom fields vary per organization), so only the stable,+# built-in columns are described here — the rest fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "people": {+ "description": "A person in the Sift directory — an employee profile with built-in and organization-specific fields.",+ "docs_url": "https://developers.justsift.com",+ "columns": {+ "id": "The unique identifier of the person.",+ "firstName": "The person's first name.",+ "lastName": "The person's last name.",+ "email": "The person's email address.",+ "directoryId": "The identifier of the directory the person belongs to.",+ "pictureUrl": "The URL of the person's profile photo (custom or official).",+ "teamLeaderId": "The id of the person's direct leader.",+ "isTeamLeader": "Whether the person has any direct reports.",+ "directReportCount": "The number of people who report directly to this person.",+ "totalReportCount": "The total number of direct and indirect reports.",+ "reportingPath": "The ordered list of leader ids from the top of the hierarchy down to this person.",+ },+ },+ "fields": {+ "description": "A field definition in the Sift schema — describes a searchable property that can appear on a person profile.",+ "docs_url": "https://developers.justsift.com",+ "columns": {+ "objectKey": "The stable key that identifies the field and is used to reference it in person objects, sorting, and filters.",+ "name": "The human-readable display name of the field.",+ "type": "The data type of the field's values.",+ "kind": "The category of the field (for example built-in or custom).",+ "searchable": "Whether the field can be used as a search filter.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/justsift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/justsift.pynew file mode 100644index 000000000000..084804f66fc8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/justsift.py@@ -0,0 +1,149 @@+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 products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.justsift.settings import JUSTSIFT_ENDPOINTS++JUSTSIFT_BASE_URL = "https://api.justsift.com/v1"+# Sift caps pageSize at 100 (default 10); 100 minimises round trips over a typically modest+# people directory and field catalog.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm a data token is genuine and can read people. The token is+# org-wide, so one probe validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/search/people"+++class JustSiftRetryableError(Exception):+ pass+++class JustSiftResumeConfig:+ # Next page to fetch (1-indexed). Page-number pagination is deterministic, so a crashed+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on the+ # primary key.+ next_page: int = 1+++def _headers(api_key: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((JustSiftRetryableError, 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,+ path: str,+ page: int,+ page_size: int,+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.get(+ f"{JUSTSIFT_BASE_URL}{path}",+ params={"page": page, "pageSize": page_size},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise JustSiftRetryableError(f"Sift API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Sift API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JustSiftResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = JUSTSIFT_ENDPOINTS[endpoint]+ # `redact_values` masks the bearer token in logged URLs and captured samples.+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume else 1+ if resume and resume.next_page > 1:+ logger.debug(f"Sift: resuming {endpoint} from page {page}")++ while True:+ data = _fetch_page(session, config.path, page, PAGE_SIZE, logger)++ # `data` is always present in the Sift envelope ({data, links, meta}); missing it means a+ # malformed response, so fail loudly rather than silently advancing past lost rows.+ items = data["data"]+ if items:+ yield items++ # Terminate on a short or empty page, or once the reported total has been covered. `/fields`+ # returns the whole catalog in one short page; `/search/people` paginates through the total.+ total = data.get("meta", {}).get("totalLength")+ if len(items) < PAGE_SIZE or (total is not None and page * PAGE_SIZE >= total):+ break++ page += 1+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(JustSiftResumeConfig(next_page=page))+++def justsift_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JustSiftResumeConfig],+) -> SourceResponse:+ config = JUSTSIFT_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_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,+ )+++def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single list endpoint to validate the data token.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise. Sift returns clean HTTP status codes for an+ invalid or scope-limited token, so no body sniffing is needed.+ """+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(f"{JUSTSIFT_BASE_URL}{path}", params={"page": 1, "pageSize": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Sift: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Sift returned HTTP {response.status_code}"++ return 200, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/settings.pynew file mode 100644index 000000000000..780636a76c8f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/settings.py@@ -0,0 +1,31 @@+from dataclasses import dataclass, field+from typing import Optional+++@dataclass+class JustSiftEndpointConfig:+ name: str+ path: str+ # Every Sift object exposes a stable unique identifier — `id` for people, `objectKey` for the+ # field-definition catalog. Both are org-unique, so a single key suffices per table.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Sift's list endpoints expose no server-side creation timestamp to partition by, so this stays+ # unset and every table is imported as a single partition.+ partition_key: Optional[str] = None+++# Sift (JustSift) API list endpoints. People are only listable through the search endpoint+# (`/search/people` with an empty query returns the whole directory, paginated); there is no+# `GET /people` that returns everyone. All endpoints are full-refresh only: Sift exposes no+# server-side `updated_after`-style filter, so there is no genuine incremental cursor to advance.+JUSTSIFT_ENDPOINTS: dict[str, JustSiftEndpointConfig] = {+ "people": JustSiftEndpointConfig(name="people", path="/search/people"),+ # A field's `objectKey` is the stable identifier used throughout the API (person keys, sortBy,+ # filters), so it is the natural primary key for the field catalog.+ "fields": JustSiftEndpointConfig(name="fields", path="/fields", primary_keys=["objectKey"]),+}++ENDPOINTS = tuple(JUSTSIFT_ENDPOINTS.keys())++# Full refresh only — no endpoint advertises an incremental cursor.+INCREMENTAL_FIELDS: dict[str, list] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/source.pyindex 7a2b9a2d1e88..421e5f57659f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/source.py@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom 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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import JustSiftSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.justsift.justsift import (+ JustSiftResumeConfig,+ check_access,+ justsift_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.justsift.settings import (+ ENDPOINTS,+ JUSTSIFT_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class JustSiftSource(SimpleSource[JustSiftSourceConfig]):+class JustSiftSource(ResumableSource[JustSiftSourceConfig, JustSiftResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.JUSTSIFT@@ -24,7 +47,96 @@ class JustSiftSource(SimpleSource[JustSiftSourceConfig]):name=SchemaExternalDataSourceType.JUST_SIFT,category=DataWarehouseSourceCategory.HR___RECRUITING,label="JustSift",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter a Sift API token to pull your organization's people directory and field catalog into the PostHog Data warehouse.++Create a token in the [Sift admin dashboard](https://admin.justsift.com) under **API Access → New Application**, granting it access to **full people data**. This read-only token is sent as a bearer token to Sift's REST API.+""",iconPath="/static/services/justsift.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/justsift",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.justsift.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid, revoked, or scope-limited token surfaces as a requests HTTPError when+ # `_fetch_page` calls `raise_for_status()`. Retrying can never satisfy a credential+ # problem, so stop the sync. Match the stable status text and base host, not the+ # per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.justsift.com": "Your Sift API token is invalid or has been revoked. Create a new token under API Access → New Application in the Sift admin dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.justsift.com": "Your Sift API token does not have access to this data. Ensure the application is granted full people data access (not photos-only), then reconnect.",+ }++ def get_schemas(+ self,+ config: JustSiftSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — Sift's list endpoints expose no server-side+ # timestamp filter, so there is no incremental cursor to advance.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: JustSiftSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The token is org-wide, so a single probe validates access to every schema; there is no+ # per-endpoint scope to check.+ status, message = check_access(config.api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Sift API token"+ return False, message or "Could not validate Sift API token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[JustSiftResumeConfig]:+ return ResumableSourceManager[JustSiftResumeConfig](inputs, JustSiftResumeConfig)++ def source_for_pipeline(+ self,+ config: JustSiftSourceConfig,+ resumable_source_manager: ResumableSourceManager[JustSiftResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in JUSTSIFT_ENDPOINTS:+ raise ValueError(f"Unknown Sift schema '{inputs.schema_name}'")++ return justsift_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/tests/test_justsift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/tests/test_justsift.pynew file mode 100644index 000000000000..8d6b377d694b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/tests/test_justsift.py@@ -0,0 +1,217 @@+from typing import Any++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.justsift import justsift+from products.warehouse_sources.backend.temporal.data_imports.sources.justsift.justsift import (+ PAGE_SIZE,+ JustSiftResumeConfig,+ JustSiftRetryableError,+ check_access,+ get_rows,+ justsift_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.justsift.settings import (+ ENDPOINTS,+ JUSTSIFT_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = justsift._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: JustSiftResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[JustSiftResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> JustSiftResumeConfig | None:+ return self._state++ def save_state(self, data: JustSiftResumeConfig) -> None:+ self.saved.append(data)+++def _envelope(items: list[dict], total: int | None = None) -> dict[str, Any]:+ meta: dict[str, Any] = {}+ if total is not None:+ meta["totalLength"] = total+ return {"data": items, "links": {}, "meta": meta}+++def _full_page(seq: int) -> dict[str, Any]:+ # A page that is exactly PAGE_SIZE long, so termination relies on the total, not a short page.+ return _envelope([{"id": f"{seq}-{i}"} for i in range(PAGE_SIZE)])+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, dict], endpoint: str = "people"+ ) -> list[dict]:+ def fake_fetch(session: Any, path: str, page: int, page_size: int, logger: Any) -> dict:+ return pages[page]++ monkeypatch.setattr(justsift, "_fetch_page", fake_fetch)+ monkeypatch.setattr(justsift, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="sift-token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_short_page_yields_items_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _envelope([{"id": "a"}, {"id": "b"}])})+ assert rows == [{"id": "a"}, {"id": "b"}]+ # A short page ends the sync, so no resume state is persisted.+ assert manager.saved == []++ def test_follows_pagination_until_short_page(self, monkeypatch: Any) -> None:+ pages = {+ 1: _full_page(1),+ 2: _full_page(2),+ 3: _envelope([{"id": "tail"}]),+ }+ rows = self._collect(_FakeResumableManager(), monkeypatch, pages)+ assert len(rows) == PAGE_SIZE * 2 + 1+ assert rows[-1] == {"id": "tail"}++ def test_terminates_when_total_is_covered_by_full_page(self, monkeypatch: Any) -> None:+ # A final page that is exactly PAGE_SIZE long still terminates because the reported total is+ # reached — without this the loop would fetch a spurious empty page.+ rows = self._collect(+ _FakeResumableManager(), monkeypatch, {1: _full_page(1) | {"meta": {"totalLength": PAGE_SIZE}}}+ )+ assert len(rows) == PAGE_SIZE++ def test_saves_next_page_after_yielding_each_batch(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ 1: _full_page(1),+ 2: _envelope([{"id": "last"}]),+ }+ self._collect(manager, monkeypatch, pages)+ # State is saved AFTER page 1 is yielded (pointing at page 2), never for the final page.+ assert [s.next_page for s in manager.saved] == [2]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(JustSiftResumeConfig(next_page=2))+ pages = {+ # Page 1 must never be fetched on resume.+ 2: _full_page(2),+ 3: _envelope([{"id": "z"}]),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert len(rows) == PAGE_SIZE + 1+ assert rows[-1] == {"id": "z"}++ def test_empty_first_page_does_not_yield(self, monkeypatch: Any) -> None:+ rows = self._collect(_FakeResumableManager(), monkeypatch, {1: _envelope([])})+ assert rows == []+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: dict | None = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body or {}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(JustSiftRetryableError):+ _fetch_page_unwrapped(session, "/search/people", 1, PAGE_SIZE, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "/search/people", 1, PAGE_SIZE, MagicMock())++ def test_success_returns_json_body(self) -> None:+ body = _envelope([{"id": "a"}], total=1)+ session = self._session_returning(200, body)+ result = _fetch_page_unwrapped(session, "/search/people", 1, PAGE_SIZE, MagicMock())+ assert result == body++ def test_request_uses_page_and_page_size_params(self) -> None:+ session = self._session_returning(200, _envelope([]))+ _fetch_page_unwrapped(session, "/fields", 3, PAGE_SIZE, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"page": 3, "pageSize": PAGE_SIZE}+++class TestCheckAccess:+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ monkeypatch.setattr(justsift, "make_tracked_session", lambda **kwargs: session)+ return session++ # monkeypatch is a pytest fixture, which parameterized.expand cannot inject — keep pytest.mark.parametrize here.+ @pytest.mark.parametrize(+ "status, ok, expected_status, expected_message",+ [+ (200, True, 200, None),+ (401, False, 401, None),+ (403, False, 403, None),+ (500, False, 500, "Sift returned HTTP 500"),+ ],+ )+ def test_status_mapping(+ self, status: int, ok: bool, expected_status: int, expected_message: str | None, monkeypatch: Any+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ self._patch_session(monkeypatch, response)+ assert check_access("sift-token") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))+ status, message = check_access("sift-token")+ assert status == 0+ assert message is not None and "boom" in message+++class TestJustSiftSourceResponse:+ @parameterized.expand([("people", ["id"]), ("fields", ["objectKey"])])+ def test_primary_keys_match_endpoint_config(self, endpoint: str, primary_keys: list[str]) -> None:+ response = justsift_source(+ api_key="sift-token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ # No endpoint exposes a creation timestamp, so nothing is partitioned by datetime.+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_endpoint_catalog_matches_exported_tuple(self) -> None:+ assert set(JUSTSIFT_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/tests/test_justsift_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/tests/test_justsift_source.pynew file mode 100644index 000000000000..5a08465ffc59--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/justsift/tests/test_justsift_source.py@@ -0,0 +1,151 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import JustSiftSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.justsift.justsift import JustSiftResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.justsift.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.justsift.source import JustSiftSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestJustSiftSource:+ def setup_method(self) -> None:+ self.source = JustSiftSource()+ self.team_id = 123+ self.config = JustSiftSourceConfig(api_key="sift-token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.JUSTSIFT++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "JustSift"+ assert config.label == "JustSift"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible — it must not carry the scaffolding flag.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/justsift"++ 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_no_connection_host_fields(self) -> None:+ # The only field is the secret token itself; the base URL is hardcoded and the org is implicit+ # in the token. There is no non-secret field that retargets where the token is sent.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static catalog with no I/O, so the public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # Sift's list endpoints have no server-side timestamp filter, 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=["fields"])+ assert len(schemas) == 1+ assert schemas[0].name == "fields"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ # Exercises the credential-free catalog path used by the posthog.com docs.+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.justsift.com/v1/search/people?page=1&pageSize=100",),+ ("403 Client Error: Forbidden for url: https://api.justsift.com/v1/fields?page=1&pageSize=100",),+ ]+ )+ 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)++ @parameterized.expand(+ [+ ("500 Server Error: Internal Server Error for url: https://api.justsift.com/v1/search/people",),+ ("HTTPSConnectionPool(host='api.justsift.com', port=443): Read timed out.",),+ ("429 Client Error: Too Many Requests for url: https://api.justsift.com/v1/fields",),+ ]+ )+ def test_non_retryable_errors_ignore_transient(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)++ @parameterized.expand(+ [+ (200, True, None),+ (401, False, "Invalid Sift API token"),+ (403, False, "Invalid Sift API token"),+ (500, False, "Sift returned HTTP 500"),+ (0, False, "Could not connect to Sift: boom"),+ ]+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.justsift.source.check_access")+ def test_validate_credentials(+ self,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_check: mock.MagicMock,+ ) -> None:+ message = (+ "Sift returned HTTP 500" if status == 500 else ("Could not connect to Sift: boom" if status == 0 else None)+ )+ mock_check.return_value = (status, message)+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)+ assert is_valid is expected_valid+ assert returned == expected_message++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.justsift.source.check_access")+ def test_validate_credentials_probes_the_token(self, mock_check: mock.MagicMock) -> None:+ # The token is org-wide, so validation probes the token, not a per-schema scope.+ mock_check.return_value = (200, None)+ self.source.validate_credentials(self.config, self.team_id, schema_name="fields")+ mock_check.assert_called_once_with("sift-token")++ 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 JustSiftResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.justsift.source.justsift_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_justsift_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "people"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_justsift_source.assert_called_once()+ kwargs = mock_justsift_source.call_args.kwargs+ assert kwargs["api_key"] == "sift-token"+ assert kwargs["endpoint"] == "people"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Sift schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)