: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): add SingleStore import source (#84457)
Tom Owers4e6998280e29
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/singlestore.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/singlestore.pyindex 1a36e8e1a31c..49ffcc8127d1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/singlestore.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/singlestore.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass SinglestoreSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/canonical_descriptions.pynew file mode 100644index 000000000000..242c92ba4b37--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/canonical_descriptions.py@@ -0,0 +1,78 @@+"""Canonical, documentation-sourced descriptions for SingleStore Management API endpoints.++Sourced from the official Management API overview and reference+(https://docs.singlestore.com/cloud/reference/management-api/) plus the field names confirmed+against SingleStore's own `singlestoredb-python` SDK source. Keyed by the resource names in+`settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced table. 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 = {+ "organization": {+ "description": "The SingleStore Helios organization the API key belongs to.",+ "docs_url": "https://docs.singlestore.com/cloud/reference/management-api/",+ "columns": {+ "orgID": "Unique identifier of the organization.",+ "name": "Name of the organization.",+ "firewallRanges": "IP ranges allowed to connect to the organization's resources.",+ },+ },+ "regions": {+ "description": "A cloud region SingleStore Helios can deploy workspace groups into.",+ "docs_url": "https://docs.singlestore.com/cloud/reference/management-api/",+ "columns": {+ "regionID": "Unique identifier of the region.",+ "region": "Human-readable name of the region.",+ "provider": "Cloud provider hosting the region (AWS, GCP, or Azure).",+ "regionName": "Provider-specific region name (e.g. us-east-1).",+ },+ },+ "workspace_groups": {+ "description": "A SingleStore Helios workspace group — the deployment unit that holds one "+ "or more workspaces sharing storage, networking, and region.",+ "docs_url": "https://docs.singlestore.com/cloud/reference/management-api/",+ "columns": {+ "workspaceGroupID": "Unique identifier of the workspace group.",+ "name": "Name of the workspace group.",+ "createdAt": "Time the workspace group was created.",+ "terminatedAt": "Time the workspace group was terminated, if applicable.",+ "regionID": "Identifier of the region the workspace group is deployed in.",+ "firewallRanges": "IP ranges allowed to connect to workspaces in this group.",+ "allowAllTraffic": "Whether inbound traffic from any IP address is allowed.",+ },+ },+ "workspaces": {+ "description": "A SingleStore Helios workspace — a compute cluster within a workspace "+ "group that runs queries against the group's shared storage.",+ "docs_url": "https://docs.singlestore.com/cloud/reference/management-api/",+ "columns": {+ "workspaceID": "Unique identifier of the workspace.",+ "workspaceGroupID": "Identifier of the workspace group this workspace belongs to.",+ "name": "Name of the workspace.",+ "size": "Workspace size in SingleStore size notation (e.g. S-00, S-1).",+ "state": "Current state of the workspace (e.g. ACTIVE, SUSPENDED, RESUMING).",+ "createdAt": "Time the workspace was created.",+ "terminatedAt": "Time the workspace was terminated, if applicable.",+ "endpoint": "Hostname used to connect to the workspace's database server.",+ "cacheConfig": "Multiplier applied to the workspace's persistent cache.",+ "deploymentType": "Deployment type of the workspace (PRODUCTION or NON-PRODUCTION).",+ },+ },+ "billing_usage": {+ "description": "Compute credit and storage usage for the organization, broken down by "+ "resource and time window.",+ "docs_url": "https://docs.singlestore.com/cloud/reference/management-api/",+ "columns": {+ "metric": "Usage metric this row measures (compute credits or average storage bytes).",+ "description": "Human-readable description of the metric.",+ "startTime": "Start of the usage interval this row covers.",+ "endTime": "End of the usage interval this row covers.",+ "resourceName": "Name of the resource (e.g. workspace) the usage is attributed to.",+ "value": "Usage value for the metric over this interval.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/settings.pynew file mode 100644index 000000000000..f79597895a92--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/settings.py@@ -0,0 +1,93 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++ORGANIZATION_ENDPOINT = "organization"+REGIONS_ENDPOINT = "regions"+WORKSPACE_GROUPS_ENDPOINT = "workspace_groups"+WORKSPACES_ENDPOINT = "workspaces"+BILLING_USAGE_ENDPOINT = "billing_usage"++# Bounds how far back the first `billing_usage` sync (or any full-refresh run) reaches. The+# Management API requires an explicit startTime/endTime window on every call; this isn't a claim+# about how far back SingleStore retains usage history.+BILLING_USAGE_DEFAULT_LOOKBACK_DAYS = 30++# `aggregateBy` value sent on every billing/usage request (hour|day|month, per the Management+# API). Day keeps row counts small for a management-API-sized dataset while still catching+# day-to-day cost swings.+BILLING_USAGE_AGGREGATE_BY = "day"+++@dataclass(frozen=True)+class SinglestoreEndpointConfig:+ name: str+ # Path appended to the versioned base URL (https://api.singlestore.com/v1).+ path: str+ primary_keys: list[str]+ # True when the response body is a single JSON object rather than an array+ # (`organizations/current`) — the row list is that one object.+ is_single_object: bool = False+ # Must be a STABLE datetime field (never `updated_at`/a mutable status) so partitions don't+ # rewrite on every sync.+ partition_key: str | None = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++SINGLESTORE_ENDPOINTS: dict[str, SinglestoreEndpointConfig] = {+ # GET /v1/organizations/current -> a single Organization object (orgID, name, firewallRanges).+ ORGANIZATION_ENDPOINT: SinglestoreEndpointConfig(+ name=ORGANIZATION_ENDPOINT,+ path="organizations/current",+ primary_keys=["orgID"],+ is_single_object=True,+ ),+ # GET /v1/regions -> raw array of Region objects (regionID, region, provider, regionName).+ # No documented pagination or filter — full refresh.+ REGIONS_ENDPOINT: SinglestoreEndpointConfig(+ name=REGIONS_ENDPOINT,+ path="regions",+ primary_keys=["regionID"],+ ),+ # GET /v1/workspaceGroups -> raw array of WorkspaceGroup objects. No updated/created-since+ # filter is documented, so this is full refresh.+ WORKSPACE_GROUPS_ENDPOINT: SinglestoreEndpointConfig(+ name=WORKSPACE_GROUPS_ENDPOINT,+ path="workspaceGroups",+ primary_keys=["workspaceGroupID"],+ partition_key="createdAt",+ ),+ # GET /v1/workspaces?workspaceGroupID={id} -> raw array of Workspace objects. There is no+ # top-level workspace listing, so this is fanned out over every workspace group id. `state`+ # (suspended/resumed/resizing) has no time filter, so this is full refresh.+ WORKSPACES_ENDPOINT: SinglestoreEndpointConfig(+ name=WORKSPACES_ENDPOINT,+ path="workspaces",+ primary_keys=["workspaceID"],+ partition_key="createdAt",+ ),+ # GET /v1/billing/usage?startTime&endTime&aggregateBy -> {"billingUsage": [{"metric",+ # "description", "usage": [{startTime, endTime, ownerID/ownerId, resourceID/resourceId,+ # resourceName, resourceType, value}]}]}. The only endpoint with a server-side time filter, so+ # it's the one incremental stream; everything else above is a small, full-refresh dimension.+ BILLING_USAGE_ENDPOINT: SinglestoreEndpointConfig(+ name=BILLING_USAGE_ENDPOINT,+ path="billing/usage",+ primary_keys=["metric", "resourceName", "startTime"],+ partition_key="startTime",+ incremental_fields=[+ {+ "label": "startTime",+ "type": IncrementalFieldType.DateTime,+ "field": "startTime",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+}++ENDPOINTS = tuple(SINGLESTORE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SINGLESTORE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/singlestore.py b/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/singlestore.pynew file mode 100644index 000000000000..965a029e083b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/singlestore.py@@ -0,0 +1,233 @@+from collections.abc import Iterator+from datetime import UTC, datetime, timedelta+from typing import Any, Optional++from jsonpath_ng import DatumInContext, JSONPath++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.rest_source import (+ ClientConfig,+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import IncrementalConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.singlestore.settings import (+ BILLING_USAGE_AGGREGATE_BY,+ BILLING_USAGE_DEFAULT_LOOKBACK_DAYS,+ BILLING_USAGE_ENDPOINT,+ SINGLESTORE_ENDPOINTS,+ WORKSPACE_GROUPS_ENDPOINT,+ WORKSPACES_ENDPOINT,+ SinglestoreEndpointConfig,+)++SINGLESTORE_BASE_URL = "https://api.singlestore.com/v1"+++def validate_credentials(api_key: str) -> tuple[bool, Optional[str]]:+ """Probe GET /v1/organizations/current — every organization API key can read its own+ organization, so this is the cheapest call that actually exercises the token. A bad key+ returns 401; SingleStore has no documented 403-but-valid-token scope split on this endpoint.+ """+ ok, status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{SINGLESTORE_BASE_URL}/organizations/current",+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ )+ if ok:+ return True, None+ if status in (401, 403):+ return (+ False,+ "SingleStore rejected the API key. Generate a new organization API key in the Cloud Portal and try again.",+ )+ # A rate limit, a transient 5xx, or an unreachable API is not a credential rejection — the+ # same conditions are retried during the sync itself, and a genuine auth failure still+ # surfaces there via get_non_retryable_errors().+ return True, None+++def _client_config(api_key: str) -> ClientConfig:+ return {+ "base_url": SINGLESTORE_BASE_URL,+ # Framework auth so the key is redacted from logs and raised error messages.+ "auth": {"type": "bearer", "token": api_key},+ "headers": {"Accept": "application/json"},+ "session": make_tracked_session(redact_values=(api_key,)),+ }+++def _list_resource(config: SinglestoreEndpointConfig, client: ClientConfig, team_id: int, job_id: str) -> Resource:+ """A single-request endpoint. Array bodies are used as the row list directly; the one+ `is_single_object` endpoint (`organizations/current`) is a bare object, which the framework's+ no-selector path wraps into a single-row list — so neither case needs a custom data_selector.+ """+ rest_config: RESTAPIConfig = {+ "client": client,+ "resources": [+ {+ "name": config.name,+ "table_format": "delta",+ "endpoint": {+ "path": config.path,+ "paginator": SinglePagePaginator(),+ # A single JSON object is the expected (and only) shape for that endpoint, so+ # `data_selector_required` would incorrectly fail it — only array endpoints get+ # the fail-loud shape check.+ "data_selector_required": not config.is_single_object,+ },+ }+ ],+ }+ return rest_api_resource(rest_config, team_id, job_id, db_incremental_field_last_value=None)+++def _iter_workspaces(client: RESTClient) -> Iterator[list[dict[str, Any]]]:+ """Fan `workspaces` out over every workspace group id — SingleStore has no top-level workspace+ listing; `GET /v1/workspaces` requires `workspaceGroupID`. Each workspace already carries its+ own `workspaceGroupID` field, so no parent field needs to be stamped onto the child rows.++ Hand-rolled rather than the declarative `"resolve"` fan-out: that mechanism only binds a+ resolved parent field into a URL *path* segment (`_bind_path_params` raises+ `NotImplementedError` otherwise), and `workspaceGroupID` here is a query parameter, not a path+ segment.+ """+ for group_page in client.paginate(+ path=SINGLESTORE_ENDPOINTS[WORKSPACE_GROUPS_ENDPOINT].path,+ paginator=SinglePagePaginator(),+ data_selector_required=True,+ ):+ for group in group_page:+ group_id = group.get("workspaceGroupID")+ if not group_id:+ continue+ yield from client.paginate(+ path=SINGLESTORE_ENDPOINTS[WORKSPACES_ENDPOINT].path,+ params={"workspaceGroupID": group_id},+ paginator=SinglePagePaginator(),+ data_selector_required=True,+ )+++def _workspaces_resource(api_key: str) -> Resource:+ client = RESTClient(+ base_url=SINGLESTORE_BASE_URL,+ headers={"Accept": "application/json"},+ auth=BearerTokenAuth(api_key),+ session=make_tracked_session(redact_values=(api_key,)),+ )++ def _generator() -> Iterator[list[dict[str, Any]]]:+ yield from _iter_workspaces(client)++ return Resource(_generator, name=WORKSPACES_ENDPOINT, hints={"table_format": "delta"})+++class _BillingUsageSelector(JSONPath):+ """Flatten `{"billingUsage": [{"metric", "description", "usage": [...]}]}` into one row per+ usage item, stamped with its parent `metric` and `description`. A declarative `data_selector`+ can select a nested list but can't also carry fields down from that list's parent object, so+ this mirrors the per-endpoint custom-selector pattern used elsewhere in the framework (e.g.+ bland_ai's pathways selector).+ """++ def find(self, data: Any) -> list[DatumInContext]:+ rows: list[dict[str, Any]] = []+ for group in (data or {}).get("billingUsage") or []:+ metric = group.get("metric")+ description = group.get("description")+ for item in group.get("usage") or []:+ rows.append({**item, "metric": metric, "description": description})+ return [DatumInContext(rows)]+++def _format_billing_timestamp(value: Any) -> str:+ """ISO 8601 UTC, matching the format the Management API's startTime/endTime filters accept."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def _billing_usage_resource(+ client: ClientConfig,+ team_id: int,+ job_id: str,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+) -> Resource:+ lookback_start = datetime.now(UTC) - timedelta(days=BILLING_USAGE_DEFAULT_LOOKBACK_DAYS)+ incremental: IncrementalConfig = {+ "start_param": "startTime",+ "end_param": "endTime",+ "cursor_path": "startTime",+ "initial_value": _format_billing_timestamp(lookback_start),+ "end_value": _format_billing_timestamp(datetime.now(UTC)),+ "convert": _format_billing_timestamp,+ "row_order": "asc",+ }+ rest_config: RESTAPIConfig = {+ "client": client,+ "resources": [+ {+ "name": BILLING_USAGE_ENDPOINT,+ "table_format": "delta",+ "write_disposition": (+ {"disposition": "merge", "strategy": "upsert"} if should_use_incremental_field else "replace"+ ),+ "endpoint": {+ "path": SINGLESTORE_ENDPOINTS[BILLING_USAGE_ENDPOINT].path,+ "params": {"aggregateBy": BILLING_USAGE_AGGREGATE_BY},+ "incremental": incremental,+ "data_selector": _BillingUsageSelector(),+ "paginator": SinglePagePaginator(),+ },+ }+ ],+ }+ return rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value=(db_incremental_field_last_value if should_use_incremental_field else None),+ )+++def singlestore_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = SINGLESTORE_ENDPOINTS[endpoint]++ if endpoint == WORKSPACES_ENDPOINT:+ resource = _workspaces_resource(api_key)+ elif endpoint == BILLING_USAGE_ENDPOINT:+ resource = _billing_usage_resource(+ _client_config(api_key), team_id, job_id, should_use_incremental_field, db_incremental_field_last_value+ )+ else:+ resource = _list_resource(config, _client_config(api_key), team_id, job_id)++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Full-refresh endpoints have no server-side order guarantee; billing_usage requests+ # `startTime` ascending via the incremental window, so asc holds for every endpoint.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/source.pyindex b477f03db031..f17f721715a7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/source.py@@ -1,33 +1,115 @@-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.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.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.singlestore import (SinglestoreSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.singlestore.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.singlestore.singlestore import (+ singlestore_source,+ validate_credentials as validate_singlestore_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass SinglestoreSource(SimpleSource[SinglestoreSourceConfig]):+ # get_schemas below just iterates the static ENDPOINTS catalog — no network call.+ lists_tables_without_credentials = True+ api_docs_url = "https://docs.singlestore.com/cloud/reference/management-api/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SINGLESTORE+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your SingleStore API key is invalid or has been revoked. Generate a new "+ "organization API key in the Cloud Portal and reconnect.",+ "403 Client Error": "Your SingleStore API key does not have permission to access this resource.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.singlestore.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: SinglestoreSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: SinglestoreSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_singlestore_credentials(config.api_key)++ def source_for_pipeline(self, config: SinglestoreSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return singlestore_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.SINGLESTORE,category=DataWarehouseSourceCategory.DATABASES,- keywords=["sql"],+ keywords=["database", "usage", "billing"],label="SingleStore, Inc.",iconPath="/static/services/singlestore.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/singlestore",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ caption="Generate an organization API key from the SingleStore Cloud Portal "+ "(Org name -> API Keys).",+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/tests/test_singlestore.py b/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/tests/test_singlestore.pynew file mode 100644index 000000000000..f7116cc9ead6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/tests/test_singlestore.py@@ -0,0 +1,334 @@+import json+from datetime import UTC, datetime+from typing import Any, cast++import pytest+from unittest import mock++import requests+from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.singlestore.settings import (+ BILLING_USAGE_ENDPOINT,+ ORGANIZATION_ENDPOINT,+ REGIONS_ENDPOINT,+ SINGLESTORE_ENDPOINTS,+ WORKSPACE_GROUPS_ENDPOINT,+ WORKSPACES_ENDPOINT,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.singlestore.singlestore import (+ SINGLESTORE_BASE_URL,+ singlestore_source,+ validate_credentials,+)++# Every builder in singlestore.py reaches for its own `make_tracked_session(...)` call, so a+# single module-level patch covers the declarative resources and the hand-rolled workspaces client.+SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.singlestore.singlestore.make_tracked_session"+)+# tenacity sleeps between retries; patch it so retry-exhaustion tests don't actually wait.+SLEEP_PATCH = "tenacity.nap.time.sleep"+++def _response(status: int, body: Any, url: str = f"{SINGLESTORE_BASE_URL}/organizations/current") -> Response:+ resp = Response()+ resp.status_code = status+ resp._content = b"" if body is None else json.dumps(body).encode()+ resp.url = url+ return resp+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session; return a list capturing each request's url + params AT SEND TIME."""+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {})})+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++def _run(endpoint: str, responses: list[Response], **kwargs: Any) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+ with mock.patch(SESSION_PATCH) as make_session:+ session = mock.MagicMock()+ snapshots = _wire(session, responses)+ make_session.return_value = session+ rows = _rows(singlestore_source(api_key="k", endpoint=endpoint, team_id=1, job_id="j", **kwargs))+ return rows, snapshots+++class TestListEndpoints:+ @parameterized.expand(+ [+ (REGIONS_ENDPOINT, f"{SINGLESTORE_BASE_URL}/regions", "regionID"),+ (WORKSPACE_GROUPS_ENDPOINT, f"{SINGLESTORE_BASE_URL}/workspaceGroups", "workspaceGroupID"),+ ]+ )+ def test_yields_dicts_from_raw_array_at_expected_url(self, endpoint: str, expected_url: str, pk: str) -> None:+ rows, snapshots = _run(endpoint, [_response(200, [{pk: "a"}, {pk: "b"}], url=expected_url)])+ assert [r[pk] for r in rows] == ["a", "b"]+ assert [s["url"] for s in snapshots] == [expected_url]++ def test_non_list_response_on_array_endpoint_raises(self) -> None:+ # A malformed body (object instead of array) must fail the sync loudly rather than+ # silently replacing the warehouse table with zero rows.+ with pytest.raises(ValueError):+ _run(REGIONS_ENDPOINT, [_response(200, {"unexpected": "shape"})])++ def test_empty_array_yields_no_rows(self) -> None:+ rows, _ = _run(REGIONS_ENDPOINT, [_response(200, [])])+ assert rows == []++ def test_single_object_endpoint_yields_one_row(self) -> None:+ # organizations/current returns a bare object, not an array; it must still become one row.+ rows, snapshots = _run(+ ORGANIZATION_ENDPOINT,+ [_response(200, {"orgID": "org1", "name": "Acme", "firewallRanges": ["0.0.0.0/0"]})],+ )+ assert rows == [{"orgID": "org1", "name": "Acme", "firewallRanges": ["0.0.0.0/0"]}]+ assert [s["url"] for s in snapshots] == [f"{SINGLESTORE_BASE_URL}/organizations/current"]+++class TestWorkspacesFanOut:+ def test_fans_out_over_every_workspace_group(self) -> None:+ rows, snapshots = _run(+ WORKSPACES_ENDPOINT,+ [+ _response(+ 200,+ [{"workspaceGroupID": "wg1"}, {"workspaceGroupID": "wg2"}],+ url=f"{SINGLESTORE_BASE_URL}/workspaceGroups",+ ),+ _response(200, [{"workspaceID": "ws1", "workspaceGroupID": "wg1"}]),+ _response(200, [{"workspaceID": "ws2", "workspaceGroupID": "wg2"}]),+ ],+ )+ assert [r["workspaceID"] for r in rows] == ["ws1", "ws2"]+ assert [s["url"] for s in snapshots] == [+ f"{SINGLESTORE_BASE_URL}/workspaceGroups",+ f"{SINGLESTORE_BASE_URL}/workspaces",+ f"{SINGLESTORE_BASE_URL}/workspaces",+ ]+ assert [s["params"].get("workspaceGroupID") for s in snapshots[1:]] == ["wg1", "wg2"]++ def test_no_workspace_groups_yields_no_workspaces(self) -> None:+ rows, _ = _run(WORKSPACES_ENDPOINT, [_response(200, [], url=f"{SINGLESTORE_BASE_URL}/workspaceGroups")])+ assert rows == []++ def test_workspace_group_missing_id_is_skipped(self) -> None:+ # A group row missing its id can't be fanned out into a `workspaceGroupID` filter; skip it+ # rather than sending a request with an empty/garbage value.+ rows, snapshots = _run(+ WORKSPACES_ENDPOINT,+ [+ _response(+ 200,+ [{"workspaceGroupID": "wg1"}, {"name": "no id"}],+ url=f"{SINGLESTORE_BASE_URL}/workspaceGroups",+ ),+ _response(200, [{"workspaceID": "ws1", "workspaceGroupID": "wg1"}]),+ ],+ )+ assert [r["workspaceID"] for r in rows] == ["ws1"]+ assert len(snapshots) == 2+++class TestBillingUsage:+ def _billing_response(self, groups: list[dict[str, Any]]) -> Response:+ return _response(200, {"billingUsage": groups}, url=f"{SINGLESTORE_BASE_URL}/billing/usage")++ def test_flattens_usage_items_and_stamps_metric_and_description(self) -> None:+ rows, _ = _run(+ BILLING_USAGE_ENDPOINT,+ [+ self._billing_response(+ [+ {+ "metric": "computeCredit",+ "description": "Compute credits used",+ "usage": [+ {+ "startTime": "2026-01-01T00:00:00Z",+ "endTime": "2026-01-02T00:00:00Z",+ "resourceName": "ws1",+ "value": "1.5",+ }+ ],+ },+ {+ "metric": "storageAvgByte",+ "description": "Average storage bytes",+ "usage": [+ {+ "startTime": "2026-01-01T00:00:00Z",+ "endTime": "2026-01-02T00:00:00Z",+ "resourceName": "ws1",+ "value": "1000",+ }+ ],+ },+ ]+ )+ ],+ )+ assert rows == [+ {+ "startTime": "2026-01-01T00:00:00Z",+ "endTime": "2026-01-02T00:00:00Z",+ "resourceName": "ws1",+ "value": "1.5",+ "metric": "computeCredit",+ "description": "Compute credits used",+ },+ {+ "startTime": "2026-01-01T00:00:00Z",+ "endTime": "2026-01-02T00:00:00Z",+ "resourceName": "ws1",+ "value": "1000",+ "metric": "storageAvgByte",+ "description": "Average storage bytes",+ },+ ]++ def test_empty_billing_usage_yields_no_rows(self) -> None:+ rows, _ = _run(BILLING_USAGE_ENDPOINT, [self._billing_response([])])+ assert rows == []++ def test_missing_billing_usage_key_yields_no_rows_rather_than_raising(self) -> None:+ # Documented as a best-effort selector: an unexpected body shape degrades to zero rows+ # instead of failing the sync, since the exact live shape isn't verified against an account.+ rows, _ = _run(BILLING_USAGE_ENDPOINT, [_response(200, {"unexpected": "shape"})])+ assert rows == []++ def test_full_refresh_requests_default_lookback_window(self) -> None:+ _, snapshots = _run(BILLING_USAGE_ENDPOINT, [self._billing_response([])])+ params = snapshots[0]["params"]+ assert params["aggregateBy"] == "day"+ start = datetime.strptime(params["startTime"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)+ end = datetime.strptime(params["endTime"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)+ assert (end - start).days == 30++ def test_incremental_sync_requests_window_from_last_value(self) -> None:+ last_value = datetime(2026, 1, 1, 12, 0, 0, tzinfo=UTC)+ _, snapshots = _run(+ BILLING_USAGE_ENDPOINT,+ [self._billing_response([])],+ should_use_incremental_field=True,+ db_incremental_field_last_value=last_value,+ )+ assert snapshots[0]["params"]["startTime"] == "2026-01-01T12:00:00Z"++ @parameterized.expand([(False, "replace"), (True, {"disposition": "merge", "strategy": "upsert"})])+ def test_write_disposition_matches_incremental_flag(+ self, should_use_incremental_field: bool, expected: Any+ ) -> None:+ # Full refresh must replace the table wholesale; an incremental sync must merge on+ # primary_keys instead of duplicating rows already synced by an earlier window.+ with mock.patch(SESSION_PATCH) as make_session:+ session = mock.MagicMock()+ _wire(session, [self._billing_response([])])+ make_session.return_value = session+ response = singlestore_source(+ api_key="k",+ endpoint=BILLING_USAGE_ENDPOINT,+ team_id=1,+ job_id="j",+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC)+ if should_use_incremental_field+ else None,+ )+ resource = cast(Resource, response.items())+ assert resource._hints.get("write_disposition") == expected+++class TestRetryAndAuthClassification:+ @mock.patch(SLEEP_PATCH)+ def test_persistent_5xx_raises_after_retries(self, _sleep: Any) -> None:+ with mock.patch(SESSION_PATCH) as make_session:+ session = mock.MagicMock()+ session.headers = {}+ session.prepare_request.side_effect = lambda request: mock.MagicMock()+ session.send.side_effect = lambda *a, **k: _response(500, {"error": "boom"})+ make_session.return_value = session+ with pytest.raises(Exception):+ _rows(singlestore_source(api_key="k", endpoint=REGIONS_ENDPOINT, team_id=1, job_id="j"))+ assert session.send.call_count > 1++ @parameterized.expand([(401,), (403,)])+ def test_auth_errors_raise_immediately(self, status: int) -> None:+ with mock.patch(SESSION_PATCH) as make_session:+ session = mock.MagicMock()+ session.headers = {}+ session.prepare_request.side_effect = lambda request: mock.MagicMock()+ session.send.side_effect = lambda *a, **k: _response(status, {"error": "denied"})+ make_session.return_value = session+ with pytest.raises(requests.HTTPError):+ _rows(singlestore_source(api_key="k", endpoint=REGIONS_ENDPOINT, team_id=1, job_id="j"))+ assert session.send.call_count == 1+++class TestValidateCredentials:+ @parameterized.expand([(200, True), (401, False), (403, False), (429, True), (500, True)])+ def test_status_mapping(self, status: int, expected_ok: bool) -> None:+ response = mock.MagicMock(status_code=status)+ session = mock.MagicMock()+ session.get.return_value = response+ with mock.patch(SESSION_PATCH, lambda *a, **k: session):+ ok, error = validate_credentials("k")+ assert ok is expected_ok+ assert (error is None) is expected_ok++ def test_probes_organizations_current_with_bearer_auth(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = mock.MagicMock(status_code=200)+ with mock.patch(SESSION_PATCH, lambda *a, **k: session):+ validate_credentials("secret")+ args, kwargs = session.get.call_args+ assert args[0] == f"{SINGLESTORE_BASE_URL}/organizations/current"+ assert kwargs["headers"]["Authorization"] == "Bearer secret"++ def test_request_exception_does_not_block_creation(self) -> None:+ # An unreachable API is transient, not a credential rejection; a genuine auth failure+ # still surfaces at sync time.+ session = mock.MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with mock.patch(SESSION_PATCH, lambda *a, **k: session):+ ok, error = validate_credentials("k")+ assert ok is True+ assert error is None+++class TestSourceResponseShape:+ @parameterized.expand(+ [+ (ORGANIZATION_ENDPOINT, ["orgID"]),+ (REGIONS_ENDPOINT, ["regionID"]),+ (WORKSPACE_GROUPS_ENDPOINT, ["workspaceGroupID"]),+ (WORKSPACES_ENDPOINT, ["workspaceID"]),+ (BILLING_USAGE_ENDPOINT, ["metric", "resourceName", "startTime"]),+ ]+ )+ def test_primary_keys_and_sort_mode(self, endpoint: str, expected_pk: list[str]) -> None:+ with mock.patch(SESSION_PATCH, lambda *a, **k: mock.MagicMock(headers={})):+ response = singlestore_source(api_key="k", endpoint=endpoint, team_id=1, job_id="j")+ assert response.name == endpoint+ assert response.primary_keys == expected_pk+ assert response.sort_mode == "asc"++ def test_every_declared_endpoint_has_a_response(self) -> None:+ with mock.patch(SESSION_PATCH, lambda *a, **k: mock.MagicMock(headers={})):+ for endpoint, config in SINGLESTORE_ENDPOINTS.items():+ response = singlestore_source(api_key="k", endpoint=endpoint, team_id=1, job_id="j")+ assert response.primary_keys == config.primary_keysdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/tests/test_singlestore_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/tests/test_singlestore_source.pynew file mode 100644index 000000000000..f428f06c7fa4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/singlestore/tests/test_singlestore_source.py@@ -0,0 +1,155 @@+from typing import Any, cast++from unittest import mock+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.singlestore import (+ SinglestoreSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.singlestore import (+ source as singlestore_source_module,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.singlestore.source import SinglestoreSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _source_inputs(schema_name: str, **overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": schema_name,+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestSinglestoreSource:+ def setup_method(self) -> None:+ self.source = SinglestoreSource()+ self.config = SinglestoreSourceConfig(api_key="key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SINGLESTORE++ def test_source_config_metadata(self) -> None:+ config = self.source.get_source_config+ assert config.label == "SingleStore, Inc."+ assert config.category == DataWarehouseSourceCategory.DATABASES+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/singlestore"+ # A finished source must never ship hidden behind this flag.+ assert config.unreleasedSource is not True++ def test_source_config_fields(self) -> None:+ fields = {f.name: cast(SourceFieldInputConfig, f) for f in self.source.get_source_config.fields}+ assert set(fields) == {"api_key"}+ assert fields["api_key"].required is True+ assert fields["api_key"].secret is True++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas iterates a static catalog with no I/O, so the public docs render the table list.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}+ assert set(schemas) == {"organization", "regions", "workspace_groups", "workspaces", "billing_usage"}++ @parameterized.expand(+ [+ ("organization",),+ ("regions",),+ ("workspace_groups",),+ ("workspaces",),+ ]+ )+ def test_dimension_schemas_are_full_refresh(self, name: str) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []++ def test_billing_usage_schema_is_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}+ assert schemas["billing_usage"].supports_incremental is True+ assert [f["field"] for f in schemas["billing_usage"].incremental_fields] == ["startTime"]++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["regions"])+ assert [s.name for s in schemas] == ["regions"]++ def test_documented_tables_render_without_credentials(self) -> None:+ tables = {t["name"]: t for t in self.source.get_documented_tables()}+ assert set(tables) == {"organization", "regions", "workspace_groups", "workspaces", "billing_usage"}+ assert tables["organization"]["description"]+ assert tables["billing_usage"]["sync_methods"] == ["Incremental", "Full refresh"]++ @parameterized.expand(+ [+ ("valid", (True, None)),+ (+ "invalid",+ (+ False,+ "SingleStore rejected the API key. Generate a new organization API key in the Cloud Portal and try again.",+ ),+ ),+ ]+ )+ def test_validate_credentials_delegates(self, _name: str, result: tuple) -> None:+ with mock.patch.object(singlestore_source_module, "validate_singlestore_credentials", lambda api_key: result):+ assert self.source.validate_credentials(self.config, team_id=1) == result++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.singlestore.com/v1/organizations/current",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.singlestore.com/v1/workspaces"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("rate_limit", "429 Client Error: Too Many Requests for url: https://api.singlestore.com/v1/workspaces"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.singlestore.com/v1/regions"),+ ("read_timeout", "HTTPSConnectionPool(host='api.singlestore.com', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ captured: dict[str, Any] = {}++ def fake_singlestore_source(**kwargs: Any) -> MagicMock:+ captured.update(kwargs)+ return MagicMock(name="source_response")++ inputs = _source_inputs(+ "billing_usage", should_use_incremental_field=True, db_incremental_field_last_value="2026-01-01"+ )+ with mock.patch.object(singlestore_source_module, "singlestore_source", fake_singlestore_source):+ self.source.source_for_pipeline(self.config, inputs)++ assert captured["api_key"] == "key"+ assert captured["endpoint"] == "billing_usage"+ assert captured["should_use_incremental_field"] is True+ assert captured["db_incremental_field_last_value"] == "2026-01-01"