Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement split_io import source (#69365)

Tom Owersf5a936ae2497
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 9caddcce63c3..425d642be4e6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -332,6 +332,7 @@ the row lists both.
| snowflake | DB protocol | snowflake-connector-python | ➖ |
| solarwinds_service_desk | HTTP | requests | ✅ |
| sparkpost | HTTP | requests | ✅ |
+| split_io | HTTP | requests | ✅ |
| square | HTTP | requests | ✅ |
| squarespace | HTTP | requests | ✅ |
| statuspage | HTTP | requests | ✅ |
@@ -703,7 +704,6 @@ doesn't conflict with concurrent PRs.
- smartengage
- smartwaiver
- sonar_cloud
-- split_io
- spotify_ads
- spotlercrm
- statsig
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 537ce2b81125..620d495790da 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
@@ -3227,7 +3227,7 @@ class SparkPostSourceConfig(config.Config):
@config.config
class SplitIoSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/canonical_descriptions.py
new file mode 100644
index 000000000000..c360a40ab772
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/canonical_descriptions.py
@@ -0,0 +1,127 @@
+"""Canonical, documentation-sourced descriptions for Split (Harness FME) endpoints and columns.
+
+Sourced from the official Split Admin API reference (https://docs.split.io/reference).
+Keyed by the endpoint names in `settings.py` `SPLIT_IO_ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced Split table. Fan-out endpoints carry an injected
+`_workspace_id` column identifying the workspace the row was fetched from. Columns absent here
+fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "workspaces": {
+ "description": "A Split workspace — a container for environments, traffic types, feature flags, and segments.",
+ "docs_url": "https://docs.split.io/reference/workspaces-overview",
+ "columns": {
+ "id": "Unique identifier for the workspace.",
+ "name": "The workspace's human-readable name.",
+ "requiresTitleAndComments": "Whether changes in this workspace require a title and comments.",
+ },
+ },
+ "environments": {
+ "description": "An environment within a Split workspace (e.g. production, staging).",
+ "docs_url": "https://docs.split.io/reference/environments-overview",
+ "columns": {
+ "id": "Unique identifier for the environment.",
+ "_workspace_id": "Id of the workspace this environment belongs to (injected during sync).",
+ "name": "The environment's name, unique within its workspace.",
+ "production": "Whether the environment is flagged as a production environment.",
+ },
+ },
+ "traffic_types": {
+ "description": "A traffic type within a Split workspace — the kind of entity flags are evaluated against (e.g. user, account).",
+ "docs_url": "https://docs.split.io/reference/traffic-types-overview",
+ "columns": {
+ "id": "Unique identifier for the traffic type.",
+ "_workspace_id": "Id of the workspace this traffic type belongs to (injected during sync).",
+ "name": "The traffic type's name, unique within its workspace.",
+ "displayAttributeId": "The attribute used as the display name for keys of this traffic type.",
+ },
+ },
+ "feature_flags": {
+ "description": "A feature flag (split) within a Split workspace.",
+ "docs_url": "https://docs.split.io/reference/feature-flags-overview",
+ "columns": {
+ "id": "Unique identifier for the feature flag.",
+ "_workspace_id": "Id of the workspace this flag belongs to (injected during sync).",
+ "name": "The flag's name, unique within its workspace.",
+ "description": "Human-readable description of the flag.",
+ "trafficType": "The traffic type the flag is evaluated against.",
+ "creationTime": "Time the flag was created, as an epoch-millisecond timestamp.",
+ "rolloutStatus": "The flag's rollout status (e.g. pre-production, ramping, 100% released).",
+ "rolloutStatusTimestamp": "Time the rollout status last changed, as an epoch-millisecond timestamp.",
+ "tags": "Tags applied to the flag.",
+ "owners": "Users and groups that own the flag.",
+ },
+ },
+ "segments": {
+ "description": "A segment within a Split workspace — a manually curated list of keys flags can target.",
+ "docs_url": "https://docs.split.io/reference/segments-overview",
+ "columns": {
+ "_workspace_id": "Id of the workspace this segment belongs to (injected during sync).",
+ "name": "The segment's name, unique within its workspace.",
+ "description": "Human-readable description of the segment.",
+ "trafficType": "The traffic type of the keys in the segment.",
+ "creationTime": "Time the segment was created, as an epoch-millisecond timestamp.",
+ "tags": "Tags applied to the segment.",
+ },
+ },
+ "rollout_statuses": {
+ "description": "A rollout status available in a Split workspace, used to track a flag's lifecycle stage.",
+ "docs_url": "https://docs.split.io/reference/rollout-statuses-overview",
+ "columns": {
+ "id": "Unique identifier for the rollout status.",
+ "_workspace_id": "Id of the workspace this rollout status belongs to (injected during sync).",
+ "name": "The rollout status's name.",
+ "description": "Human-readable description of the rollout status.",
+ },
+ },
+ "flag_sets": {
+ "description": "A flag set within a Split workspace — a named grouping of feature flags evaluated together.",
+ "docs_url": "https://docs.split.io/reference/flag-sets-overview",
+ "columns": {
+ "id": "Unique identifier for the flag set.",
+ "_workspace_id": "Id of the workspace this flag set belongs to (injected during sync).",
+ "name": "The flag set's name, unique within its workspace.",
+ "description": "Human-readable description of the flag set.",
+ },
+ },
+ "groups": {
+ "description": "A group of users in the Split organization.",
+ "docs_url": "https://docs.split.io/reference/groups-overview",
+ "columns": {
+ "id": "Unique identifier for the group.",
+ "name": "The group's name, unique within the organization.",
+ "description": "Human-readable description of the group.",
+ },
+ },
+ "users": {
+ "description": "A member of the Split organization.",
+ "docs_url": "https://docs.split.io/reference/users-overview",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "name": "The user's full name.",
+ "email": "The user's email address.",
+ "status": "The user's status (e.g. ACTIVE, DEACTIVATED).",
+ "groups": "Groups the user belongs to.",
+ "2fa": "Whether the user has two-factor authentication enabled.",
+ },
+ },
+ "change_requests": {
+ "description": "A change request — a proposed change to a feature flag or segment awaiting approval.",
+ "docs_url": "https://docs.split.io/reference/change-requests-overview",
+ "columns": {
+ "id": "Unique identifier for the change request.",
+ "status": "The change request's status (e.g. REQUESTED, APPROVED, PUBLISHED, WITHDRAWN).",
+ "title": "Title of the change request.",
+ "comment": "Comment submitted with the change request.",
+ "split": "The feature flag definition the change applies to, if any.",
+ "segment": "The segment the change applies to, if any.",
+ "operationType": "The kind of change being requested (e.g. UPDATE, ARCHIVE).",
+ "approvers": "Users asked to approve the change.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/settings.py
new file mode 100644
index 000000000000..b857dc220553
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/settings.py
@@ -0,0 +1,119 @@
+from dataclasses import dataclass, field
+from typing import Literal
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# How a list endpoint pages through results:
+# - "offset": `limit`/`offset` params with an `{"objects": [...], "offset", "limit", "totalCount"}` envelope
+# - "marker": `limit`/`after` params, with `nextMarker`/`previousMarker` in the response envelope
+# (rows sit under `data` or `objects` depending on the endpoint)
+# - "none": the endpoint returns the full collection as a plain JSON array in one response
+PaginationStyle = Literal["offset", "marker", "none"]
+
+
+@dataclass
+class SplitIoEndpointConfig:
+ name: str
+ # Path under the API root. A ``{workspace_id}`` placeholder marks a fan-out endpoint
+ # that must be queried once per workspace.
+ path: str
+ primary_keys: list[str]
+ pagination: PaginationStyle = "offset"
+ # Envelope key holding the rows (None for plain-array responses).
+ data_key: str | None = "objects"
+ # Fan-out endpoints depend on the list of workspaces; we inject ``_workspace_id`` into
+ # every row so a single table stays meaningful (and uniquely keyed) across workspaces.
+ requires_workspace: bool = False
+ # Some fan-out endpoints take the workspace as a query param instead of a path segment.
+ workspace_query_param: str | None = None
+ # Extra query params required by the endpoint.
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # Most endpoints live under /internal/api/v2; flag sets are served from v3.
+ api_version: str = "v2"
+
+
+# Split (Harness FME) Admin API v2 endpoints. All are full-refresh only: the Admin API exposes
+# no server-side timestamp filter (`since`/`updated_after`) on any of these resources — its
+# timestamps are epoch-millisecond integers with no range query params — so there is no
+# reliable incremental cursor to advance.
+SPLIT_IO_ENDPOINTS: dict[str, SplitIoEndpointConfig] = {
+ "workspaces": SplitIoEndpointConfig(
+ name="workspaces",
+ path="/workspaces",
+ primary_keys=["id"],
+ ),
+ "environments": SplitIoEndpointConfig(
+ name="environments",
+ path="/environments/ws/{workspace_id}",
+ primary_keys=["id"],
+ pagination="none",
+ data_key=None,
+ requires_workspace=True,
+ ),
+ "traffic_types": SplitIoEndpointConfig(
+ name="traffic_types",
+ path="/trafficTypes/ws/{workspace_id}",
+ primary_keys=["id"],
+ pagination="none",
+ data_key=None,
+ requires_workspace=True,
+ ),
+ "feature_flags": SplitIoEndpointConfig(
+ name="feature_flags",
+ path="/splits/ws/{workspace_id}",
+ # Flag names are unique only within a workspace, so the composite key includes the
+ # injected ``_workspace_id``.
+ primary_keys=["name", "_workspace_id"],
+ requires_workspace=True,
+ ),
+ "segments": SplitIoEndpointConfig(
+ name="segments",
+ path="/segments/ws/{workspace_id}",
+ # Segment list objects carry no id — they are keyed by name within a workspace.
+ primary_keys=["name", "_workspace_id"],
+ requires_workspace=True,
+ ),
+ "rollout_statuses": SplitIoEndpointConfig(
+ name="rollout_statuses",
+ path="/rolloutStatuses",
+ primary_keys=["id"],
+ pagination="none",
+ data_key=None,
+ requires_workspace=True,
+ workspace_query_param="wsId",
+ ),
+ "flag_sets": SplitIoEndpointConfig(
+ name="flag_sets",
+ path="/flag-sets",
+ primary_keys=["id"],
+ pagination="marker",
+ data_key="data",
+ requires_workspace=True,
+ workspace_query_param="workspace_id",
+ api_version="v3",
+ ),
+ "groups": SplitIoEndpointConfig(
+ name="groups",
+ path="/groups",
+ primary_keys=["id"],
+ pagination="marker",
+ ),
+ "users": SplitIoEndpointConfig(
+ name="users",
+ path="/users",
+ primary_keys=["id"],
+ pagination="marker",
+ data_key="data",
+ ),
+ "change_requests": SplitIoEndpointConfig(
+ name="change_requests",
+ path="/changeRequests",
+ primary_keys=["id"],
+ pagination="marker",
+ data_key="data",
+ ),
+}
+
+ENDPOINTS = tuple(SPLIT_IO_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/source.py
index ef7454ecbf3f..15979162808f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SplitIoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.split_io.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ SPLIT_IO_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io import (
+ SplitIoResumeConfig,
+ split_io_source,
+ validate_credentials as validate_split_io_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SplitIoSource(SimpleSource[SplitIoSourceConfig]):
+class SplitIoSource(ResumableSource[SplitIoSourceConfig, SplitIoResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SPLITIO
@@ -23,8 +47,104 @@ class SplitIoSource(SimpleSource[SplitIoSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.SPLIT_IO,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
+ keywords=["harness", "fme", "feature flags", "experimentation"],
label="Split.io",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Split (Harness FME) Admin API key to pull your workspaces, environments, feature flags, segments, and change requests into the PostHog Data warehouse.
+
+You can create an Admin API key in Split under **Admin settings → API keys** — choose the **Admin** type (client- and server-side SDK keys won't work). The key grants read access to every resource this source syncs.""",
iconPath="/static/services/split_io.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/split-io",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Admin API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.split_io.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.split.io": "Your Split Admin API key is invalid or has been revoked. Create a new Admin API key under Admin settings → API keys, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.split.io": "Your Split API key does not have permission for this resource. Make sure the key is an Admin (org-scoped) API key, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: SplitIoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # The Split Admin API exposes no server-side timestamp filter on these resources,
+ # so every endpoint is full-refresh only (no incremental/append support).
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(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: SplitIoSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if schema_name is not None and schema_name not in SPLIT_IO_ENDPOINTS:
+ return False, f"Unknown Split schema '{schema_name}'"
+
+ status = validate_split_io_credentials(config.api_key, schema_name)
+
+ if status is None:
+ return False, "Could not reach the Split API. Please try again."
+ if status == 401:
+ return False, "Invalid Split Admin API key"
+ # A valid key may legitimately lack scope for a specific endpoint. Accept 403 at
+ # source-create (schema_name is None); only reject it for a specific schema check.
+ if status == 403:
+ if schema_name is None:
+ return True, None
+ return False, f"Your API key does not have permission to read '{schema_name}'"
+ if status >= 400:
+ return False, f"Split returned an unexpected status ({status})"
+ return True, None
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SplitIoResumeConfig]:
+ return ResumableSourceManager[SplitIoResumeConfig](inputs, SplitIoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SplitIoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SplitIoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in SPLIT_IO_ENDPOINTS:
+ raise ValueError(f"Unknown Split schema '{inputs.schema_name}'")
+
+ return split_io_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/split_io/split_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/split_io.py
new file mode 100644
index 000000000000..644180ccae7c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/split_io.py
@@ -0,0 +1,308 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import parse_qs, urlencode, urlsplit, urlunsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt
+
+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.split_io.settings import (
+ SPLIT_IO_ENDPOINTS,
+ SplitIoEndpointConfig,
+)
+
+API_HOST = "https://api.split.io"
+BASE_URL = f"{API_HOST}/internal/api/v2"
+
+# Offset-paginated list endpoints document a max `limit` of 200 but some resources cap lower;
+# 50 is accepted across the board, and the offset advances by the actual row count so a lower
+# server-side clamp only costs extra requests, never skipped rows.
+PAGE_SIZE = 50
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+MAX_RETRY_WAIT_SECONDS = 60
+
+
+class SplitIoRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None):
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class SplitIoResumeConfig:
+ # Full URL of the next page to fetch ("" once a resource is exhausted).
+ next_url: str = ""
+ # For fan-out endpoints, the workspace currently being paginated ("" for top-level
+ # endpoints or before the first workspace starts).
+ workspace_id: str = ""
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _base_url(config: SplitIoEndpointConfig) -> str:
+ return f"{API_HOST}/internal/api/{config.api_version}"
+
+
+def _initial_url(config: SplitIoEndpointConfig, workspace_id: str = "") -> str:
+ path = config.path.format(workspace_id=workspace_id)
+ params: dict[str, Any] = dict(config.extra_params)
+ if config.workspace_query_param and workspace_id:
+ params[config.workspace_query_param] = workspace_id
+ if config.pagination != "none":
+ params["limit"] = PAGE_SIZE
+ query = urlencode(params)
+ base = _base_url(config)
+ return f"{base}{path}?{query}" if query else f"{base}{path}"
+
+
+def _replace_query_param(url: str, key: str, value: str) -> str:
+ scheme, netloc, path, query, fragment = urlsplit(url)
+ params = {k: v[-1] for k, v in parse_qs(query).items()}
+ params[key] = value
+ return urlunsplit((scheme, netloc, path, urlencode(params), fragment))
+
+
+def _query_param(url: str, key: str) -> str | None:
+ values = parse_qs(urlsplit(url).query).get(key)
+ return values[-1] if values else None
+
+
+def _extract_items(payload: Any, data_key: str | None) -> list[dict[str, Any]]:
+ if isinstance(payload, list):
+ return payload
+ if not isinstance(payload, dict):
+ raise SplitIoRetryableError(f"Split returned an unexpected payload type: {type(payload).__name__}")
+ # Fall back to the other documented envelope key — the Admin API wraps rows in either
+ # `objects` (offset endpoints) or `data` (marker endpoints), and per-endpoint docs drift.
+ for key in filter(None, (data_key, "objects", "data")):
+ items = payload.get(key)
+ if isinstance(items, list):
+ return items
+ return []
+
+
+def _next_url(config: SplitIoEndpointConfig, url: str, payload: Any, items: list[dict[str, Any]]) -> str | None:
+ if config.pagination == "none" or not isinstance(payload, dict) or not items:
+ return None
+
+ if config.pagination == "marker":
+ next_marker = payload.get("nextMarker")
+ if not next_marker or not isinstance(next_marker, str):
+ return None
+ # A marker equal to the one we just requested means the server ignored the param;
+ # stop rather than loop on the same page forever.
+ if next_marker == _query_param(url, "after"):
+ return None
+ return _replace_query_param(url, "after", next_marker)
+
+ # Offset pagination: advance by the number of rows actually returned (robust to the server
+ # clamping `limit`), terminating on `totalCount` when present.
+ offset = int(_query_param(url, "offset") or 0)
+ next_offset = offset + len(items)
+ total_count = payload.get("totalCount")
+ if isinstance(total_count, int) and next_offset >= total_count:
+ return None
+ if total_count is None and len(items) < int(_query_param(url, "limit") or PAGE_SIZE):
+ return None
+ return _replace_query_param(url, "offset", str(next_offset))
+
+
+def _wait_strategy(retry_state: Any) -> float:
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exc, SplitIoRetryableError) and exc.retry_after is not None:
+ return min(exc.retry_after, MAX_RETRY_WAIT_SECONDS)
+ return min(2.0**retry_state.attempt_number, MAX_RETRY_WAIT_SECONDS)
+
+
+@retry(
+ retry=retry_if_exception_type((SplitIoRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=_wait_strategy,
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> Any:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429:
+ retry_after_header = response.headers.get("Retry-After")
+ try:
+ retry_after = float(retry_after_header) if retry_after_header else None
+ except ValueError:
+ # A non-numeric value (e.g. an HTTP-date) falls back to exponential backoff.
+ retry_after = None
+ logger.warning(f"Split rate limited (429), retrying. retry_after={retry_after_header}, url={url}")
+ raise SplitIoRetryableError(f"Split rate limited: url={url}", retry_after=retry_after)
+
+ if response.status_code >= 500:
+ raise SplitIoRetryableError(f"Split server error: status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Split API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(api_key: str, endpoint: str | None = None) -> int | None:
+ """Probe an endpoint and return the HTTP status code (or None on transport failure).
+
+ Fan-out endpoints can't be probed without a workspace id, so they (and the default
+ source-create probe) check /workspaces — their prerequisite. Top-level endpoints probe
+ their own path.
+ """
+ config = SPLIT_IO_ENDPOINTS.get(endpoint) if endpoint else None
+ if config is None or config.requires_workspace:
+ url = f"{BASE_URL}/workspaces?{urlencode({'limit': 1})}"
+ else:
+ params: dict[str, Any] = dict(config.extra_params)
+ params["limit"] = 1
+ url = f"{_base_url(config)}{config.path}?{urlencode(params)}"
+
+ try:
+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))
+ response = session.get(url, timeout=10)
+ return response.status_code
+ except Exception:
+ return None
+
+
+def _fetch_workspace_ids(session: requests.Session, logger: FilteringBoundLogger) -> list[str]:
+ ids: list[str] = []
+ url: str | None = _initial_url(SPLIT_IO_ENDPOINTS["workspaces"])
+ while url:
+ payload = _fetch_page(session, url, logger)
+ items = _extract_items(payload, "objects")
+ # `id` is the identifier every fan-out URL is built from; fail fast rather than
+ # silently dropping a workspace (and all its flags/segments/environments) if absent.
+ for item in items:
+ ids.append(item["id"])
+ url = _next_url(SPLIT_IO_ENDPOINTS["workspaces"], url, payload, items)
+ return ids
+
+
+def _paginate_resource(
+ session: requests.Session,
+ config: SplitIoEndpointConfig,
+ start_url: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SplitIoResumeConfig],
+ workspace_id: str,
+) -> Iterator[list[dict[str, Any]]]:
+ url: str | None = start_url
+ previous_fingerprint: tuple[int, str] | None = None
+ while url:
+ payload = _fetch_page(session, url, logger)
+ items = _extract_items(payload, config.data_key)
+
+ # If the server ignores our pagination params and keeps returning the same page,
+ # stop rather than yield duplicates forever (fingerprint taken before mutation).
+ fingerprint = (len(items), str(items[0])) if items else None
+ if fingerprint is not None and fingerprint == previous_fingerprint:
+ logger.warning(f"Split: identical page returned twice, stopping pagination. endpoint={config.name}")
+ break
+ previous_fingerprint = fingerprint
+
+ if workspace_id:
+ for item in items:
+ item["_workspace_id"] = workspace_id
+
+ if items:
+ yield items
+
+ next_url = _next_url(config, url, payload, items)
+ # Save state AFTER yielding so a heartbeat-timeout crash re-fetches from the next
+ # page rather than re-emitting the page we just yielded (merge dedupes regardless).
+ resumable_source_manager.save_state(SplitIoResumeConfig(next_url=next_url or "", workspace_id=workspace_id))
+ url = next_url
+
+
+def _get_fanout_rows(
+ session: requests.Session,
+ config: SplitIoEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SplitIoResumeConfig],
+ resume: SplitIoResumeConfig | None,
+) -> Iterator[list[dict[str, Any]]]:
+ workspace_ids = _fetch_workspace_ids(session, logger)
+ if not workspace_ids:
+ logger.warning(f"Split: no workspaces found, nothing to sync for endpoint={config.name}")
+ return
+
+ start_idx = 0
+ resume_url: str | None = None
+ if resume is not None and resume.workspace_id and resume.workspace_id in workspace_ids:
+ idx = workspace_ids.index(resume.workspace_id)
+ if resume.next_url:
+ # Mid-workspace: pick up at the saved page within that workspace.
+ start_idx = idx
+ resume_url = resume.next_url
+ else:
+ # The saved workspace finished (empty next_url marker); start at the next one.
+ start_idx = idx + 1
+
+ for i in range(start_idx, len(workspace_ids)):
+ workspace_id = workspace_ids[i]
+ if i == start_idx and resume_url:
+ start_url = resume_url
+ else:
+ start_url = _initial_url(config, workspace_id)
+ yield from _paginate_resource(session, config, start_url, logger, resumable_source_manager, workspace_id)
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SplitIoResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = SPLIT_IO_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.requires_workspace:
+ yield from _get_fanout_rows(session, config, logger, resumable_source_manager, resume)
+ return
+
+ if resume is not None and resume.next_url:
+ logger.debug(f"Split: resuming endpoint={endpoint} from url={resume.next_url}")
+ start_url = resume.next_url
+ else:
+ start_url = _initial_url(config)
+
+ yield from _paginate_resource(session, config, start_url, logger, resumable_source_manager, workspace_id="")
+
+
+def split_io_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SplitIoResumeConfig],
+) -> SourceResponse:
+ config = SPLIT_IO_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,
+ # Split timestamps are epoch-millisecond integers and the datetime partitioner
+ # expects epoch-seconds, so partitioning is intentionally left off to avoid
+ # mis-bucketing rows far into the future.
+ partition_mode=None,
+ partition_keys=None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/tests/test_split_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/tests/test_split_io.py
new file mode 100644
index 000000000000..9ff03823121c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/tests/test_split_io.py
@@ -0,0 +1,376 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.split_io.settings import (
+ ENDPOINTS,
+ SPLIT_IO_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io import (
+ BASE_URL,
+ PAGE_SIZE,
+ SplitIoResumeConfig,
+ _extract_items,
+ _initial_url,
+ _next_url,
+ get_rows,
+ split_io_source,
+ validate_credentials,
+)
+
+
+def _make_manager(resume_state: SplitIoResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _resp(payload: Any, status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = payload
+ resp.status_code = status_code
+ resp.ok = 200 <= status_code < 300
+ return resp
+
+
+def _offset_page(items: list[dict[str, Any]], offset: int, total_count: int) -> dict[str, Any]:
+ return {"objects": items, "offset": offset, "limit": PAGE_SIZE, "totalCount": total_count}
+
+
+class TestUrlHelpers:
+ def test_initial_url_top_level_includes_limit(self):
+ assert _initial_url(SPLIT_IO_ENDPOINTS["workspaces"]) == f"{BASE_URL}/workspaces?limit={PAGE_SIZE}"
+
+ def test_initial_url_formats_workspace_path(self):
+ url = _initial_url(SPLIT_IO_ENDPOINTS["feature_flags"], "ws-1")
+ assert url == f"{BASE_URL}/splits/ws/ws-1?limit={PAGE_SIZE}"
+
+ def test_initial_url_workspace_query_param(self):
+ url = _initial_url(SPLIT_IO_ENDPOINTS["rollout_statuses"], "ws-1")
+ assert url == f"{BASE_URL}/rolloutStatuses?wsId=ws-1"
+
+ def test_initial_url_flag_sets_uses_v3_api(self):
+ url = _initial_url(SPLIT_IO_ENDPOINTS["flag_sets"], "ws-1")
+ assert url == f"https://api.split.io/internal/api/v3/flag-sets?workspace_id=ws-1&limit={PAGE_SIZE}"
+
+ def test_initial_url_unpaginated_endpoint_has_no_limit(self):
+ url = _initial_url(SPLIT_IO_ENDPOINTS["environments"], "ws-1")
+ assert url == f"{BASE_URL}/environments/ws/ws-1"
+
+
+class TestExtractItems:
+ @pytest.mark.parametrize(
+ "payload, data_key, expected",
+ [
+ ([{"id": "1"}], None, [{"id": "1"}]),
+ ({"objects": [{"id": "1"}]}, "objects", [{"id": "1"}]),
+ ({"data": [{"id": "1"}]}, "data", [{"id": "1"}]),
+ # Envelope-key drift: rows under the other documented key are still found.
+ ({"data": [{"id": "1"}]}, "objects", [{"id": "1"}]),
+ ({"objects": [{"id": "1"}]}, "data", [{"id": "1"}]),
+ ({"unrelated": True}, "objects", []),
+ ],
+ )
+ def test_extract_items(self, payload, data_key, expected):
+ assert _extract_items(payload, data_key) == expected
+
+
+class TestNextUrl:
+ def test_offset_advances_by_row_count(self):
+ config = SPLIT_IO_ENDPOINTS["workspaces"]
+ url = f"{BASE_URL}/workspaces?limit={PAGE_SIZE}"
+ items = [{"id": str(i)} for i in range(PAGE_SIZE)]
+ next_url = _next_url(config, url, _offset_page(items, 0, PAGE_SIZE * 2), items)
+ assert next_url == f"{BASE_URL}/workspaces?limit={PAGE_SIZE}&offset={PAGE_SIZE}"
+
+ def test_offset_stops_at_total_count(self):
+ config = SPLIT_IO_ENDPOINTS["workspaces"]
+ url = f"{BASE_URL}/workspaces?limit={PAGE_SIZE}&offset={PAGE_SIZE}"
+ items = [{"id": "x"}]
+ assert _next_url(config, url, _offset_page(items, PAGE_SIZE, PAGE_SIZE + 1), items) is None
+
+ def test_offset_server_clamped_limit_keeps_paginating(self):
+ # The server may clamp `limit` below what we requested; totalCount must drive
+ # termination, not the short page.
+ config = SPLIT_IO_ENDPOINTS["workspaces"]
+ url = f"{BASE_URL}/workspaces?limit={PAGE_SIZE}"
+ items = [{"id": str(i)} for i in range(10)]
+ next_url = _next_url(config, url, _offset_page(items, 0, 30), items)
+ assert next_url == f"{BASE_URL}/workspaces?limit={PAGE_SIZE}&offset=10"
+
+ def test_offset_without_total_count_stops_on_short_page(self):
+ config = SPLIT_IO_ENDPOINTS["workspaces"]
+ url = f"{BASE_URL}/workspaces?limit={PAGE_SIZE}"
+ items = [{"id": "1"}]
+ assert _next_url(config, url, {"objects": items}, items) is None
+
+ def test_marker_advances_via_next_marker(self):
+ config = SPLIT_IO_ENDPOINTS["users"]
+ url = f"{BASE_URL}/users?limit={PAGE_SIZE}"
+ items = [{"id": "u1"}]
+ next_url = _next_url(config, url, {"data": items, "nextMarker": "m2"}, items)
+ assert next_url == f"{BASE_URL}/users?limit={PAGE_SIZE}&after=m2"
+
+ @pytest.mark.parametrize("payload", [{"data": [{"id": "u1"}]}, {"data": [{"id": "u1"}], "nextMarker": None}])
+ def test_marker_stops_without_next_marker(self, payload):
+ config = SPLIT_IO_ENDPOINTS["users"]
+ url = f"{BASE_URL}/users?limit={PAGE_SIZE}"
+ assert _next_url(config, url, payload, payload["data"]) is None
+
+ def test_marker_stops_when_server_ignores_after_param(self):
+ # A repeated marker means the server ignored `after`; stopping avoids an infinite loop.
+ config = SPLIT_IO_ENDPOINTS["users"]
+ url = f"{BASE_URL}/users?limit={PAGE_SIZE}&after=m2"
+ items = [{"id": "u1"}]
+ assert _next_url(config, url, {"data": items, "nextMarker": "m2"}, items) is None
+
+ def test_marker_reads_next_marker_from_objects_envelope(self):
+ # Groups paginate by marker but wrap rows in `objects` rather than `data`.
+ config = SPLIT_IO_ENDPOINTS["groups"]
+ url = f"{BASE_URL}/groups?limit={PAGE_SIZE}"
+ items = [{"id": "g1"}]
+ next_url = _next_url(config, url, {"objects": items, "nextMarker": "m2"}, items)
+ assert next_url == f"{BASE_URL}/groups?limit={PAGE_SIZE}&after=m2"
+
+ @pytest.mark.parametrize("payload", [[{"id": "1"}], {"objects": [{"id": "1"}]}])
+ def test_unpaginated_endpoint_never_advances(self, payload):
+ config = SPLIT_IO_ENDPOINTS["environments"]
+ items = _extract_items(payload, config.data_key)
+ assert _next_url(config, f"{BASE_URL}/environments/ws/ws-1", payload, items) is None
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize("status_code", [200, 401, 403, 500])
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_returns_status_code(self, mock_session, status_code):
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)
+ assert validate_credentials("api-key") == status_code
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_returns_none_on_exception(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("api-key") is None
+
+ @pytest.mark.parametrize(
+ "endpoint, expected_url",
+ [
+ # Source-create and fan-out endpoints probe /workspaces (their prerequisite).
+ (None, f"{BASE_URL}/workspaces?limit=1"),
+ ("feature_flags", f"{BASE_URL}/workspaces?limit=1"),
+ # Top-level endpoints probe their own path.
+ ("groups", f"{BASE_URL}/groups?limit=1"),
+ ("users", f"{BASE_URL}/users?limit=1"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_probes_the_right_endpoint(self, mock_session, endpoint, expected_url):
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+ validate_credentials("api-key", endpoint)
+ assert mock_session.return_value.get.call_args.args[0] == expected_url
+
+
+class TestGetRowsTopLevel:
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_paginates_offset_endpoint(self, mock_session):
+ first = [{"id": str(i)} for i in range(PAGE_SIZE)]
+ mock_session.return_value.get.side_effect = [
+ _resp(_offset_page(first, 0, PAGE_SIZE + 1)),
+ _resp(_offset_page([{"id": "last"}], PAGE_SIZE, PAGE_SIZE + 1)),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("api-key", "workspaces", mock.MagicMock(), manager))
+
+ ids = [item["id"] for batch in batches for item in batch]
+ assert ids == [str(i) for i in range(PAGE_SIZE)] + ["last"]
+ # State saved after every page (final save records the empty next_url marker).
+ saved_urls = [call.args[0].next_url for call in manager.save_state.call_args_list]
+ assert saved_urls == [f"{BASE_URL}/workspaces?limit={PAGE_SIZE}&offset={PAGE_SIZE}", ""]
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_resumes_from_saved_state(self, mock_session):
+ mock_session.return_value.get.return_value = _resp(_offset_page([{"id": "9"}], PAGE_SIZE, PAGE_SIZE + 1))
+
+ resume_url = f"{BASE_URL}/workspaces?limit={PAGE_SIZE}&offset={PAGE_SIZE}"
+ manager = _make_manager(SplitIoResumeConfig(next_url=resume_url))
+
+ list(get_rows("api-key", "workspaces", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.get.call_args_list[0].args[0] == resume_url
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_marker_endpoint_paginates_until_marker_exhausted(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _resp({"data": [{"id": "u1"}], "nextMarker": "m2"}),
+ _resp({"data": [{"id": "u2"}], "nextMarker": None}),
+ ]
+
+ batches = list(get_rows("api-key", "users", mock.MagicMock(), _make_manager()))
+
+ assert [item["id"] for batch in batches for item in batch] == ["u1", "u2"]
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert urls == [
+ f"{BASE_URL}/users?limit={PAGE_SIZE}",
+ f"{BASE_URL}/users?limit={PAGE_SIZE}&after=m2",
+ ]
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_empty_response_yields_nothing(self, mock_session):
+ mock_session.return_value.get.return_value = _resp({"objects": [], "nextMarker": None})
+
+ assert list(get_rows("api-key", "groups", mock.MagicMock(), _make_manager())) == []
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_identical_page_stops_pagination(self, mock_session):
+ # A server that ignores our pagination params but keeps advertising a fresh marker
+ # would otherwise loop forever re-yielding the same rows.
+ same_page = {"data": [{"id": "u1"}], "nextMarker": "m2"}
+ mock_session.return_value.get.side_effect = [
+ _resp(same_page),
+ _resp({"data": [{"id": "u1"}], "nextMarker": "m3"}),
+ _resp({"data": [{"id": "u1"}], "nextMarker": "m4"}),
+ ]
+
+ batches = list(get_rows("api-key", "users", mock.MagicMock(), _make_manager()))
+
+ # First page yielded once; the identical follow-up page halts the loop.
+ assert [item["id"] for batch in batches for item in batch] == ["u1"]
+ assert mock_session.return_value.get.call_count == 2
+
+
+class TestGetRowsFanout:
+ def _workspaces_page(self) -> mock.MagicMock:
+ return _resp(_offset_page([{"id": "ws-1"}, {"id": "ws-2"}], 0, 2))
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_iterates_workspaces_and_injects_workspace_id(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ self._workspaces_page(),
+ _resp([{"id": "e1"}]),
+ _resp([{"id": "e2"}]),
+ ]
+
+ batches = list(get_rows("api-key", "environments", mock.MagicMock(), _make_manager()))
+
+ rows = [item for batch in batches for item in batch]
+ assert rows == [
+ {"id": "e1", "_workspace_id": "ws-1"},
+ {"id": "e2", "_workspace_id": "ws-2"},
+ ]
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert urls == [
+ f"{BASE_URL}/workspaces?limit={PAGE_SIZE}",
+ f"{BASE_URL}/environments/ws/ws-1",
+ f"{BASE_URL}/environments/ws/ws-2",
+ ]
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_workspace_query_param_fanout(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _resp(_offset_page([{"id": "ws-1"}], 0, 1)),
+ _resp([{"id": "rs1"}]),
+ ]
+
+ list(get_rows("api-key", "rollout_statuses", mock.MagicMock(), _make_manager()))
+
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert urls[1] == f"{BASE_URL}/rolloutStatuses?wsId=ws-1"
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_resume_skips_completed_workspace(self, mock_session):
+ # ws-1 finished last run (empty next_url marker); resume must start at ws-2.
+ mock_session.return_value.get.side_effect = [
+ self._workspaces_page(),
+ _resp([{"id": "e2"}]),
+ ]
+ manager = _make_manager(SplitIoResumeConfig(next_url="", workspace_id="ws-1"))
+
+ batches = list(get_rows("api-key", "environments", mock.MagicMock(), manager))
+
+ rows = [item for batch in batches for item in batch]
+ assert rows == [{"id": "e2", "_workspace_id": "ws-2"}]
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert urls == [f"{BASE_URL}/workspaces?limit={PAGE_SIZE}", f"{BASE_URL}/environments/ws/ws-2"]
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_resume_midworkspace_uses_saved_url(self, mock_session):
+ resume_url = f"{BASE_URL}/splits/ws/ws-1?limit={PAGE_SIZE}&offset={PAGE_SIZE}"
+ mock_session.return_value.get.side_effect = [
+ self._workspaces_page(),
+ _resp(_offset_page([{"name": "f1b"}], PAGE_SIZE, PAGE_SIZE + 1)),
+ _resp(_offset_page([{"name": "f2"}], 0, 1)),
+ ]
+ manager = _make_manager(SplitIoResumeConfig(next_url=resume_url, workspace_id="ws-1"))
+
+ list(get_rows("api-key", "feature_flags", mock.MagicMock(), manager))
+
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert urls == [
+ f"{BASE_URL}/workspaces?limit={PAGE_SIZE}",
+ resume_url,
+ f"{BASE_URL}/splits/ws/ws-2?limit={PAGE_SIZE}",
+ ]
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_no_workspaces_yields_nothing(self, mock_session):
+ mock_session.return_value.get.return_value = _resp(_offset_page([], 0, 0))
+
+ assert list(get_rows("api-key", "feature_flags", mock.MagicMock(), _make_manager())) == []
+
+
+class TestRetryAndErrors:
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io.make_tracked_session"
+ )
+ def test_4xx_raises(self, mock_session):
+ resp = _resp({}, status_code=403)
+ resp.raise_for_status.side_effect = Exception("403 Client Error")
+ mock_session.return_value.get.return_value = resp
+
+ with pytest.raises(Exception, match="403 Client Error"):
+ list(get_rows("api-key", "workspaces", mock.MagicMock(), _make_manager()))
+
+
+class TestSplitIoSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = SPLIT_IO_ENDPOINTS[endpoint]
+ response = split_io_source("api-key", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ # Partitioning is intentionally off (epoch-ms timestamps).
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @pytest.mark.parametrize("endpoint", ["feature_flags", "segments"])
+ def test_workspace_scoped_names_use_composite_primary_key(self, endpoint):
+ assert SPLIT_IO_ENDPOINTS[endpoint].primary_keys == ["name", "_workspace_id"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/tests/test_split_io_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/tests/test_split_io_source.py
new file mode 100644
index 000000000000..93b9e87d1ae6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/split_io/tests/test_split_io_source.py
@@ -0,0 +1,124 @@
+import pytest
+from unittest import mock
+
+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 SplitIoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.split_io.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.split_io.source import SplitIoSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.split_io.split_io import SplitIoResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSplitIoSource:
+ def setup_method(self):
+ self.source = SplitIoSource()
+ self.team_id = 123
+ self.config = SplitIoSourceConfig(api_key="admin-api-key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.SPLITIO
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "SplitIo"
+ assert config.label == "Split.io"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/split_io.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):
+ 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
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.split.io/internal/api/v2/workspaces",
+ "403 Client Error: Forbidden for url: https://api.split.io/internal/api/v2/splits/ws/abc",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ def test_non_retryable_errors_does_not_match_server_errors(self):
+ observed_error = "500 Server Error for url: https://api.split.io/internal/api/v2/workspaces"
+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ def test_get_schemas_lists_all_endpoints_full_refresh(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # The Split Admin API has no server-side timestamp filter, so nothing is incremental.
+ assert all(not schema.supports_incremental for schema in schemas)
+ assert all(not schema.supports_append for schema in schemas)
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["feature_flags"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "feature_flags"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "status, schema_name, expected_valid",
+ [
+ (200, None, True),
+ (401, None, False),
+ # A valid key may lack scope for an unselected endpoint — accept 403 at source-create.
+ (403, None, True),
+ # But reject 403 when validating a specific schema.
+ (403, "feature_flags", False),
+ (500, None, False),
+ (None, None, False),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.split_io.source.validate_split_io_credentials"
+ )
+ def test_validate_credentials_status_mapping(self, mock_validate, status, schema_name, expected_valid):
+ mock_validate.return_value = status
+
+ is_valid, _error = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+
+ assert is_valid is expected_valid
+
+ def test_validate_credentials_unknown_schema_rejected_without_probe(self):
+ is_valid, error = self.source.validate_credentials(self.config, self.team_id, schema_name="nope")
+ assert is_valid is False
+ assert error is not None and "nope" in error
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SplitIoResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.split_io.source.split_io_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_split_io_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "workspaces"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_split_io_source.call_args.kwargs
+ assert kwargs["api_key"] == "admin-api-key"
+ assert kwargs["endpoint"] == "workspaces"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_rejects_unknown_schema(self):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "nope"
+
+ with pytest.raises(ValueError, match="Unknown Split schema"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)