: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 scale_ai import source (#70026)
Tom Owersf37999827584
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex e31d257f426e..2c98c6a93431 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -344,6 +344,7 @@ the row lists both.| salesflare | HTTP | requests | ✅ || salesloft | HTTP | requests | ✅ || savvycal | HTTP | requests | ✅ |+| scale_ai | HTTP | requests | ✅ || scaleway | HTTP | requests | ✅ || secoda | HTTP | requests | ✅ || segment | HTTP | requests | ✅ |@@ -763,6 +764,7 @@ doesn't conflict with concurrent PRs.- sap_successfactors- savvycal- scale_ai+- scaleway- search_ads_360- sendpulse- senseforcediff --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 39b9e2981cb5..471ab9a311a9 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@@ -3297,7 +3297,7 @@ class SavvyCalSourceConfig(config.Config):@config.configclass ScaleAISourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/canonical_descriptions.pynew file mode 100644index 000000000000..047c11db8a8f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/canonical_descriptions.py@@ -0,0 +1,50 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "tasks": {+ "description": "A unit of data labeling work submitted to Scale, with its type, status, timestamps, and review results.",+ "docs_url": "https://scale.com/docs/api-reference/tasks",+ "columns": {+ "task_id": "Unique identifier for the task.",+ "type": "The task type (e.g. imageannotation, categorization, textcollection).",+ "status": "Current lifecycle status of the task (pending, completed, or canceled).",+ "project": "Name of the project the task belongs to.",+ "batch": "Name of the batch the task belongs to, if any.",+ "created_at": "When the task was created.",+ "completed_at": "When the task was completed, if it has been.",+ "updated_at": "When the task was last updated.",+ "callback_url": "URL Scale calls when the task completes.",+ "instruction": "Instructions shown to the labeler for this task.",+ "params": "Task-type-specific parameters supplied at creation.",+ "response": "The completed labeling response, present once the task is done.",+ "metadata": "Arbitrary customer-supplied metadata attached to the task.",+ "customer_review_status": "Audit result for the task (accepted, fixed, commented, or rejected).",+ "tags": "Tags applied to the task.",+ "unique_id": "Customer-supplied unique identifier used to deduplicate task creation.",+ },+ },+ "batches": {+ "description": "A collection of tasks grouped for calibration and delivery within a project.",+ "docs_url": "https://scale.com/docs/api-reference/batches",+ "columns": {+ "name": "Unique name of the batch.",+ "project": "Name of the project the batch belongs to.",+ "status": "Current status of the batch (staging, in_progress, or completed).",+ "created_at": "When the batch was created.",+ "completed_at": "When the batch was completed, if it has been.",+ "metadata": "Arbitrary customer-supplied metadata attached to the batch.",+ },+ },+ "projects": {+ "description": "A container that defines the labeling task type and instructions shared by its tasks and batches.",+ "docs_url": "https://scale.com/docs/api-reference/projects",+ "columns": {+ "name": "Unique name of the project.",+ "type": "The task type the project produces.",+ "created_at": "When the project was created.",+ "param_history": "History of parameter/instruction versions for the project.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/scale_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/scale_ai.pynew file mode 100644index 000000000000..902c6f903779--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/scale_ai.py@@ -0,0 +1,288 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+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.batcher import Batcher+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.scale_ai.settings import (+ INCREMENTAL_PARAM_BY_FIELD,+ SCALE_AI_ENDPOINTS,+ ScaleAIEndpointConfig,+)++SCALE_AI_BASE_URL = "https://api.scale.com/v1"+++class ScaleAIRetryableError(Exception):+ pass+++class ScaleAIResumeConfig:+ # Cursor token for the `tasks` endpoint. Holds the token used to fetch the page currently+ # being processed, so a resume re-fetches that page (merge dedupes on the primary key) rather+ # than skipping the un-yielded remainder of it. None means "start from the first page".+ next_token: str | None = None+ # Offset for the `batches` endpoint, pointing at the page currently being processed for the+ # same re-fetch-on-resume reason.+ offset: int | None = None+++def _format_incremental_value(value: Any) -> str:+ """Format an incremental cursor as an ISO 8601 string, which Scale's time filters expect."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return dt.isoformat()+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()+ return str(value)+++def _auth(api_key: str) -> tuple[str, str]:+ """Scale uses HTTP Basic auth with the API key as the username and an empty password."""+ return (api_key, "")+++def _extract_docs(data: Any) -> list[dict[str, Any]]:+ """Pull the list of records out of a Scale list response.++ Tasks/batches wrap results in a `docs` envelope; projects return a bare array. Handle both+ (plus a defensive fallback) so a shape difference between endpoints stays contained here.+ """+ if isinstance(data, list):+ return data+ if isinstance(data, dict):+ for key in ("docs", "projects", "batches", "tasks"):+ value = data.get(key)+ if isinstance(value, list):+ return value+ return []+++@retry(+ retry=retry_if_exception_type(+ (+ ScaleAIRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ url: str,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.get(url, params=params, timeout=60)++ # Scale publishes no documented rate limit; treat 429 and 5xx as transient and back off.+ if response.status_code == 429 or response.status_code >= 500:+ raise ScaleAIRetryableError(f"Scale API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Scale API error: status={response.status_code}, body={response.text}, url={url}")+ # 401/403 surface here as an HTTPError; get_non_retryable_errors matches on the status text.+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str) -> bool:+ """One cheap probe against the tasks list endpoint to confirm the API key is genuine."""+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(+ f"{SCALE_AI_BASE_URL}/tasks",+ params={"limit": 1},+ auth=_auth(api_key),+ timeout=10,+ )+ return response.status_code == 200+ except Exception:+ return False+++def _build_params(+ config: ScaleAIEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ params: dict[str, Any] = {}+ if config.pagination in ("cursor", "offset"):+ params["limit"] = config.page_size++ if should_use_incremental_field and db_incremental_field_last_value:+ chosen = incremental_field or config.default_incremental_field+ param_name = INCREMENTAL_PARAM_BY_FIELD.get(chosen) if chosen else None+ if param_name:+ params[param_name] = _format_incremental_value(db_incremental_field_last_value)++ return params+++def _iter_cursor(+ session: requests.Session,+ url: str,+ base_params: dict[str, Any],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ manager: ResumableSourceManager[ScaleAIResumeConfig],+ resume: ScaleAIResumeConfig | None,+) -> Iterator[Any]:+ """Paginate a `next_token` cursor endpoint (tasks).++ The incremental `updated_after` filter in `base_params` is documented as server-side, so the+ result set is already bounded and pagination terminates when `next_token` is null (verified from+ docs; not curl-verified against a live key). If a future check finds the filter only applies to+ the first page, this loop would need a client-side stop once a page predates the watermark.+ """+ current_token = resume.next_token if resume is not None else None++ while True:+ params = dict(base_params)+ if current_token:+ params["next_token"] = current_token++ data = _fetch_page(session, url, params, logger)+ docs = _extract_docs(data)+ next_token = data.get("next_token") if isinstance(data, dict) else None++ for item in docs:+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ # Checkpoint the CURRENT page token so a crash re-fetches this page rather than+ # skipping its un-yielded remainder; merge dedupes the overlap on the primary key.+ manager.save_state(ScaleAIResumeConfig(next_token=current_token))++ if not next_token or not docs:+ break+ current_token = next_token+++def _iter_offset(+ session: requests.Session,+ url: str,+ base_params: dict[str, Any],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ manager: ResumableSourceManager[ScaleAIResumeConfig],+ resume: ScaleAIResumeConfig | None,+ page_size: int,+) -> Iterator[Any]:+ """Paginate a `limit`/`offset` endpoint (batches)."""+ offset = resume.offset if resume is not None and resume.offset is not None else 0++ while True:+ params = {**base_params, "offset": offset}+ data = _fetch_page(session, url, params, logger)+ docs = _extract_docs(data)+ if not docs:+ break++ for item in docs:+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ manager.save_state(ScaleAIResumeConfig(offset=offset))++ # A short page is the last page; a full page means another may follow.+ if len(docs) < page_size:+ break+ offset += page_size+++def _iter_single(+ session: requests.Session,+ url: str,+ base_params: dict[str, Any],+ logger: FilteringBoundLogger,+ batcher: Batcher,+) -> Iterator[Any]:+ """Fetch a single, non-paginated list (projects)."""+ data = _fetch_page(session, url, base_params, logger)+ for item in _extract_docs(data):+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ScaleAIResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[Any]:+ config = SCALE_AI_ENDPOINTS[endpoint]+ session = make_tracked_session(redact_values=(api_key,))+ session.auth = _auth(api_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)++ base_params = _build_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )+ url = f"{SCALE_AI_BASE_URL}{config.path}"+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if config.pagination == "cursor":+ yield from _iter_cursor(session, url, base_params, logger, batcher, resumable_source_manager, resume)+ elif config.pagination == "offset":+ yield from _iter_offset(+ session, url, base_params, logger, batcher, resumable_source_manager, resume, config.page_size+ )+ else:+ yield from _iter_single(session, url, base_params, logger, batcher)++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def scale_ai_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ScaleAIResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = SCALE_AI_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ 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=endpoint_config.primary_keys,+ # Scale returns every list endpoint newest-first by created_at and exposes no sort control,+ # so rows always arrive descending. "desc" persists the incremental watermark only at+ # successful job end, which is correct here: tasks filter on updated_at but arrive in+ # created_at order, so a per-batch (asc) watermark could advance past unread rows.+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/settings.pynew file mode 100644index 000000000000..4aef297dd6db--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/settings.py@@ -0,0 +1,83 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class ScaleAIEndpointConfig:+ name: str+ path: str+ # Pagination style the endpoint exposes. Tasks use a `next_token` cursor; batches use+ # `limit`/`offset`; projects return the whole list in one response (no pagination).+ pagination: Literal["cursor", "offset", "none"]+ incremental_fields: list[IncrementalField]+ default_incremental_field: Optional[str] = None+ # Stable field to partition by. Always a creation timestamp so partitions never rewrite+ # (Scale exposes no server-side sort, so `updated_at` would move rows between partitions).+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["task_id"])+ page_size: int = 100 # Scale caps `limit` at 100 for tasks+ should_sync_default: bool = True+++# Maps a user-selected incremental field to the Scale query parameter that filters on it+# server-side. Tasks accept `updated_after` (updated_at) and `start_time` (created_at); batches+# only accept `start_time` (created_at). Only fields present here can be synced incrementally.+INCREMENTAL_PARAM_BY_FIELD: dict[str, str] = {+ "updated_at": "updated_after",+ "created_at": "start_time",+}+++def _datetime_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++SCALE_AI_ENDPOINTS: dict[str, ScaleAIEndpointConfig] = {+ # Tasks are the core operational records (type, status, review results, timestamps). They+ # return newest-first by created_at and support a genuine server-side `updated_after` filter,+ # so incremental sync picks up both new tasks and updates (status/review changes) to old ones.+ "tasks": ScaleAIEndpointConfig(+ name="tasks",+ path="/tasks",+ pagination="cursor",+ primary_keys=["task_id"],+ partition_key="created_at",+ default_incremental_field="updated_at",+ incremental_fields=[_datetime_field("updated_at"), _datetime_field("created_at")],+ ),+ # Batches group tasks. The list endpoint filters only on created_at (`start_time`), which is+ # immutable, so incremental sync catches newly created batches but not status changes to old+ # ones; a full refresh re-reads status for every batch.+ "batches": ScaleAIEndpointConfig(+ name="batches",+ path="/batches",+ pagination="offset",+ primary_keys=["name"],+ partition_key="created_at",+ default_incremental_field="created_at",+ incremental_fields=[_datetime_field("created_at")],+ ),+ # Projects are a small, slowly-changing catalog with no server-side time filter, so they are+ # full-refreshed each sync.+ "projects": ScaleAIEndpointConfig(+ name="projects",+ path="/projects",+ pagination="none",+ primary_keys=["name"],+ partition_key="created_at",+ incremental_fields=[],+ ),+}++ENDPOINTS = tuple(SCALE_AI_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SCALE_AI_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/source.pyindex ebc517d28420..8ca741aac0b5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/source.py@@ -1,19 +1,43 @@-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 ScaleAISourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.scale_ai.scale_ai import (+ ScaleAIResumeConfig,+ scale_ai_source,+ validate_credentials as validate_scale_ai_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.scale_ai.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SCALE_AI_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ScaleAISource(SimpleSource[ScaleAISourceConfig]):+class ScaleAISource(ResumableSource[ScaleAISourceConfig, ScaleAIResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SCALEAI@@ -24,8 +48,106 @@ class ScaleAISource(SimpleSource[ScaleAISourceConfig]):name=SchemaExternalDataSourceType.SCALE_AI,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Scale AI",+ releaseStatus=ReleaseStatus.ALPHA,+ unreleasedSource=True,+ caption="""Enter your Scale AI API key to sync your Scale data labeling data into the PostHog Data warehouse.++You can find your API key in the [Scale dashboard](https://dashboard.scale.com/) under **Settings → API Keys**. Use a **live-mode** key — test-mode keys have fully isolated data. Only account Managers and Admins can access API keys.+""",iconPath="/static/services/scale_ai.png",+ docsUrl="https://posthog.com/docs/cdp/sources/scale-ai",keywords=["labeling", "annotation", "rlhf", "training data"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="live_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.scale_ai.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError from raise_for_status(). Retrying can never fix 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.scale.com": "Your Scale AI API key is invalid or has been revoked. Create a new live-mode key in the Scale dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.scale.com": "Your Scale AI API key does not have permission to read this data. Check the key's permissions in the Scale dashboard, then reconnect.",+ }++ def get_schemas(+ self,+ config: ScaleAISourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == "batches":+ return (+ "Incremental sync filters on created_at, so it catches newly created batches but "+ "not status changes to existing ones; use a full refresh to re-read batch status."+ )+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = SCALE_AI_ENDPOINTS[endpoint]+ has_incremental = len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ detected_primary_keys=endpoint_config.primary_keys,+ should_sync_default=endpoint_config.should_sync_default,+ description=_description(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: ScaleAISourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_scale_ai_credentials(config.api_key):+ return True, None++ return False, "Invalid Scale AI API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ScaleAIResumeConfig]:+ return ResumableSourceManager[ScaleAIResumeConfig](inputs, ScaleAIResumeConfig)++ def source_for_pipeline(+ self,+ config: ScaleAISourceConfig,+ resumable_source_manager: ResumableSourceManager[ScaleAIResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return scale_ai_source(+ api_key=config.api_key,+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/tests/test_scale_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/tests/test_scale_ai.pynew file mode 100644index 000000000000..ca0fae1350ec--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/tests/test_scale_ai.py@@ -0,0 +1,295 @@+from datetime import UTC, date, datetime+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.scale_ai import scale_ai+from products.warehouse_sources.backend.temporal.data_imports.sources.scale_ai.scale_ai import (+ ScaleAIResumeConfig,+ _build_params,+ _extract_docs,+ _format_incremental_value,+ get_rows,+ scale_ai_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.scale_ai.settings import SCALE_AI_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: ScaleAIResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[ScaleAIResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> ScaleAIResumeConfig | None:+ return self._state++ def save_state(self, data: ScaleAIResumeConfig) -> None:+ self.saved.append(data)+++class TestFormatIncrementalValue:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+00:00"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),+ ("string_passthrough", "cursor", "cursor"),+ ]+ )+ def test_format_incremental_value(self, _name: str, value: object, expected: str) -> None:+ assert _format_incremental_value(value) == expected+++class TestBuildParams:+ @parameterized.expand(+ [+ # The chosen incremental field maps to a specific server-side param; the wrong param would+ # silently ignore the cutoff and re-scan the full history every run.+ ("tasks_updated_at", "tasks", "updated_at", "updated_after"),+ ("tasks_created_at", "tasks", "created_at", "start_time"),+ ("batches_created_at", "batches", "created_at", "start_time"),+ ]+ )+ def test_incremental_field_maps_to_server_param(+ self, _name: str, endpoint: str, incremental_field: str, expected_param: str+ ) -> None:+ params = _build_params(+ SCALE_AI_ENDPOINTS[endpoint],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ incremental_field=incremental_field,+ )+ assert params[expected_param] == "2026-03-04T00:00:00+00:00"++ def test_no_incremental_param_when_disabled(self) -> None:+ params = _build_params(+ SCALE_AI_ENDPOINTS["tasks"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ incremental_field="updated_at",+ )+ assert "updated_after" not in params+ assert "start_time" not in params+ assert params["limit"] == 100++ def test_projects_has_no_limit_param(self) -> None:+ # Projects is a single non-paginated list; sending limit/offset would be meaningless.+ params = _build_params(+ SCALE_AI_ENDPOINTS["projects"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ incremental_field=None,+ )+ assert params == {}+++class TestExtractDocs:+ @parameterized.expand(+ [+ ("docs_envelope", {"docs": [{"a": 1}], "has_more": False}, [{"a": 1}]),+ ("bare_list", [{"a": 1}, {"a": 2}], [{"a": 1}, {"a": 2}]),+ ("empty_docs", {"docs": [], "total": 0}, []),+ ("unknown_shape", {"unexpected": 1}, []),+ ]+ )+ def test_extract_docs(self, _name: str, data: Any, expected: list[dict]) -> None:+ assert _extract_docs(data) == expected+++def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, endpoint: str, pages: dict[Any, Any], **kw: Any+) -> list[dict]:+ """Drive get_rows with a per-request fake fetch keyed by (next_token/offset).++ Forces a chunk size of 1 so every row triggers a yield + state save, exercising the resume+ checkpoint path that the production 2000-row chunk would hide in a small test.+ """+ calls: list[dict] = []++ def fake_fetch(session: Any, url: str, params: dict, logger: Any) -> dict:+ calls.append(dict(params))+ key = params.get("next_token", params.get("offset", "__first__"))+ return pages[key]++ monkeypatch.setattr(scale_ai, "_fetch_page", fake_fetch)+ monkeypatch.setattr(+ scale_ai,+ "Batcher",+ lambda **kwargs: Batcher(logger=kwargs["logger"], chunk_size=1, chunk_size_bytes=kwargs["chunk_size_bytes"]),+ )++ rows: list[dict] = []+ for table in get_rows(+ api_key="live_key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=cast(ResumableSourceManager[ScaleAIResumeConfig], manager),+ **kw,+ ):+ rows.extend(table.to_pylist())+ manager.last_fetch_params = calls # type: ignore[attr-defined]+ return rows+++class TestCursorPagination:+ def test_follows_next_token_until_exhausted(self, monkeypatch: Any) -> None:+ pages = {+ "__first__": {"docs": [{"task_id": "T1"}], "next_token": "tok2"},+ "tok2": {"docs": [{"task_id": "T2"}], "next_token": "tok3"},+ "tok3": {"docs": [{"task_id": "T3"}], "next_token": None},+ }+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, "tasks", pages)+ assert [r["task_id"] for r in rows] == ["T1", "T2", "T3"]++ def test_checkpoints_current_page_token_after_each_batch(self, monkeypatch: Any) -> None:+ # Resume must re-fetch the page we were on (merge dedupes), not skip to the next one.+ pages = {+ "__first__": {"docs": [{"task_id": "T1"}], "next_token": "tok2"},+ "tok2": {"docs": [{"task_id": "T2"}], "next_token": None},+ }+ manager = _FakeResumableManager()+ _collect(manager, monkeypatch, "tasks", pages)+ # First page's row checkpoints token=None (re-fetch first page); second page checkpoints tok2.+ assert [s.next_token for s in manager.saved] == [None, "tok2"]++ def test_resumes_from_saved_token(self, monkeypatch: Any) -> None:+ pages = {+ "tok2": {"docs": [{"task_id": "T2"}], "next_token": None},+ }+ manager = _FakeResumableManager(ScaleAIResumeConfig(next_token="tok2"))+ rows = _collect(manager, monkeypatch, "tasks", pages)+ # T1 (first page) is skipped because we resume mid-stream from tok2.+ assert [r["task_id"] for r in rows] == ["T2"]++ def test_incremental_cutoff_sent_on_first_request(self, monkeypatch: Any) -> None:+ pages = {"__first__": {"docs": [{"task_id": "T1"}], "next_token": None}}+ manager = _FakeResumableManager()+ _collect(+ manager,+ monkeypatch,+ "tasks",+ pages,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ incremental_field="updated_at",+ )+ assert manager.last_fetch_params[0]["updated_after"] == "2026-03-04T00:00:00+00:00" # type: ignore[attr-defined]+++class TestOffsetPagination:+ def test_walks_offsets_until_short_page(self, monkeypatch: Any) -> None:+ # batches page_size is 100; a page shorter than that ends pagination.+ full_page = [{"name": f"B{i}"} for i in range(100)]+ pages = {+ "__first__": {"docs": full_page},+ 0: {"docs": full_page},+ 100: {"docs": [{"name": "B100"}]},+ }+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, "batches", pages)+ assert len(rows) == 101+ assert rows[-1]["name"] == "B100"++ def test_stops_on_first_short_page(self, monkeypatch: Any) -> None:+ pages = {"__first__": {"docs": [{"name": "B1"}, {"name": "B2"}]}, 0: {"docs": [{"name": "B1"}, {"name": "B2"}]}}+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, "batches", pages)+ assert [r["name"] for r in rows] == ["B1", "B2"]++ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:+ pages = {100: {"docs": [{"name": "B100"}]}}+ manager = _FakeResumableManager(ScaleAIResumeConfig(offset=100))+ rows = _collect(manager, monkeypatch, "batches", pages)+ assert [r["name"] for r in rows] == ["B100"]+++class TestSingleFetch:+ def test_projects_fetches_once(self, monkeypatch: Any) -> None:+ pages = {"__first__": {"docs": [{"name": "P1"}, {"name": "P2"}]}}+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, "projects", pages)+ assert [r["name"] for r in rows] == ["P1", "P2"]+ assert len(manager.last_fetch_params) == 1 # type: ignore[attr-defined]+++class TestFetchPageRetries:+ @parameterized.expand(+ [+ ("retryable_500", 500, True),+ ("retryable_429", 429, True),+ ("fatal_401", 401, False),+ ("fatal_403", 403, False),+ ]+ )+ def test_status_handling(self, _name: str, status_code: int, retryable: bool) -> None:+ session = MagicMock()+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = {"docs": []}+ response.raise_for_status.side_effect = requests.HTTPError(f"{status_code} error", response=response)+ session.get.return_value = response++ with patch.object(scale_ai._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ if retryable:+ # Both retryable statuses raise ScaleAIRetryableError and exhaust the 5 attempts.+ with pytest.raises(scale_ai.ScaleAIRetryableError):+ scale_ai._fetch_page(session, "https://api.scale.com/v1/tasks", {}, MagicMock())+ assert session.get.call_count == 5+ else:+ with pytest.raises(requests.HTTPError):+ scale_ai._fetch_page(session, "https://api.scale.com/v1/tasks", {}, MagicMock())+ assert session.get.call_count == 1++ def test_transient_error_retried_then_succeeds(self) -> None:+ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = {"docs": []}+ session = MagicMock()+ session.get.side_effect = [requests.ReadTimeout("timed out"), good]++ with patch.object(scale_ai._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = scale_ai._fetch_page(session, "https://api.scale.com/v1/tasks", {}, MagicMock())++ assert result == {"docs": []}+ assert session.get.call_count == 2+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_maps_to_validity(self, _name: str, status_code: int, expected: bool) -> None:+ response = MagicMock(status_code=status_code)+ session = MagicMock()+ session.get.return_value = response+ with patch.object(scale_ai, "make_tracked_session", return_value=session):+ assert scale_ai.validate_credentials("live_key") is expected++ def test_network_error_is_invalid(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(scale_ai, "make_tracked_session", return_value=session):+ assert scale_ai.validate_credentials("live_key") is False+++class TestSourceResponse:+ @parameterized.expand([("tasks", ["task_id"]), ("batches", ["name"]), ("projects", ["name"])])+ def test_primary_keys_and_desc_sort(self, endpoint: str, primary_keys: list[str]) -> None:+ # sort_mode="desc" defers watermark persistence to job end — required because tasks filter on+ # updated_at but arrive in created_at order.+ response = scale_ai_source(+ api_key="live_key", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()+ )+ assert response.primary_keys == primary_keys+ assert response.sort_mode == "desc"+ assert response.partition_keys == ["created_at"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/tests/test_scale_ai_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/tests/test_scale_ai_source.pynew file mode 100644index 000000000000..a341fdb75313--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scale_ai/tests/test_scale_ai_source.py@@ -0,0 +1,154 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.scale_ai.scale_ai import ScaleAIResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.scale_ai.source import ScaleAISource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestScaleAISourceConfig:+ def test_source_type(self) -> None:+ assert ScaleAISource().source_type == ExternalDataSourceType.SCALEAI++ def test_config_identity_and_release(self) -> None:+ config = ScaleAISource().get_source_config+ assert config.name == SchemaExternalDataSourceType.SCALE_AI+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ # Ships hidden and alpha per the batch rollout plan.+ assert config.unreleasedSource is True+ assert config.releaseStatus == ReleaseStatus.ALPHA++ def test_config_requires_a_secret_api_key_field(self) -> None:+ # A non-secret or non-required key field would leak the credential or let the form submit blank.+ fields = ScaleAISource().get_source_config.fields+ assert len(fields) == 1+ api_key = fields[0]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert api_key.name == "api_key"+ assert api_key.type == SourceFieldInputConfigType.PASSWORD+ assert api_key.required is True+ assert api_key.secret is True++ def test_docs_url_matches_slug(self) -> None:+ assert ScaleAISource().get_source_config.docsUrl == "https://posthog.com/docs/cdp/sources/scale-ai"+++class TestScaleAISchemas:+ def test_lists_all_endpoints(self) -> None:+ schemas = ScaleAISource().get_schemas(MagicMock(), team_id=1)+ assert {s.name for s in schemas} == {"tasks", "batches", "projects"}++ @parameterized.expand(+ [+ ("tasks", True, ["task_id"], ["updated_at", "created_at"]),+ ("batches", True, ["name"], ["created_at"]),+ ("projects", False, ["name"], []),+ ]+ )+ def test_schema_incremental_and_keys(+ self, name: str, incremental: bool, primary_keys: list[str], incremental_fields: list[str]+ ) -> None:+ schemas = {s.name: s for s in ScaleAISource().get_schemas(MagicMock(), team_id=1)}+ schema = schemas[name]+ assert schema.supports_incremental is incremental+ assert schema.detected_primary_keys == primary_keys+ assert [f["field"] for f in schema.incremental_fields] == incremental_fields++ def test_names_filter(self) -> None:+ schemas = ScaleAISource().get_schemas(MagicMock(), team_id=1, names=["tasks"])+ assert [s.name for s in schemas] == ["tasks"]++ def test_documented_tables_render_without_credentials(self) -> None:+ # The docs Supported-tables section depends on this static, no-I/O catalog being exposed.+ tables = ScaleAISource().get_documented_tables()+ assert {t["name"] for t in tables} == {"tasks", "batches", "projects"}+ tasks = next(t for t in tables if t["name"] == "tasks")+ assert tasks["primary_keys"] == ["task_id"]+ assert tasks["description"] # canonical description flows through+++class TestScaleAICredentials:+ @parameterized.expand([("valid", True, (True, None)), ("invalid", False, (False, "Invalid Scale AI API key"))])+ def test_validate_credentials(self, _name: str, probe_result: bool, expected: tuple[bool, str | None]) -> None:+ config = MagicMock(api_key="live_key")+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.scale_ai.source.validate_scale_ai_credentials",+ return_value=probe_result,+ ):+ assert ScaleAISource().validate_credentials(config, team_id=1) == expected++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.scale.com/v1/tasks?limit=1"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.scale.com/v1/batches?limit=100"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = ScaleAISource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='api.scale.com', port=443): Read timed out."),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.scale.com/v1/tasks"),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = ScaleAISource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestScaleAIPipelineWiring:+ def test_resumable_manager_is_bound_to_resume_config(self) -> None:+ inputs = MagicMock(team_id=1, job_id="job", logger=MagicMock())+ manager = ScaleAISource().get_resumable_source_manager(inputs)+ assert manager._data_class is ScaleAIResumeConfig++ def test_source_for_pipeline_forwards_inputs(self) -> None:+ config = MagicMock(api_key="live_key")+ manager = MagicMock()+ inputs = MagicMock(+ schema_name="tasks",+ logger=MagicMock(),+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00+00:00",+ incremental_field="updated_at",+ )+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.scale_ai.source.scale_ai_source"+ ) as mock_source:+ ScaleAISource().source_for_pipeline(config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "live_key"+ assert kwargs["endpoint"] == "tasks"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00+00:00"+ assert kwargs["incremental_field"] == "updated_at"++ def test_source_for_pipeline_drops_cursor_on_full_refresh(self) -> None:+ # A stale watermark must not leak into a full-refresh run and silently filter it.+ config = MagicMock(api_key="live_key")+ inputs = MagicMock(+ schema_name="projects",+ logger=MagicMock(),+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-01-01T00:00:00+00:00",+ incremental_field=None,+ )+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.scale_ai.source.scale_ai_source"+ ) as mock_source:+ ScaleAISource().source_for_pipeline(config, MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None