:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement clickhouse_cloud import source (#71345)
Tom Owers74a5ab339d46
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 70f6243b76b3..be78af7ee4cf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -146,6 +146,7 @@ the row lists both.| clari | HTTP | requests | ✅ || clerk | HTTP | requests + `rest_source.RESTClient` | ✅ || clickhouse | DB protocol (HTTP-based) | clickhouse-connect / clickhouse-driver | ➖ |+| clickhouse_cloud | HTTP | requests | ✅ || clickup | HTTP | requests | ✅ || clockify | HTTP | requests | ✅ || clockodo | HTTP | requests | ✅ |@@ -656,7 +657,6 @@ doesn't conflict with concurrent PRs.- cisco_meraki- clarifai- clazar-- clickhouse_cloud- cloudbeds- coassemble- cockroachdbdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/canonical_descriptions.pynew file mode 100644index 000000000000..8bd167d7b699--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/canonical_descriptions.py@@ -0,0 +1,139 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the official ClickHouse Cloud OpenAPI spec+# (https://clickhouse.com/docs/cloud/manage/api/swagger).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "organizations": {+ "description": "The ClickHouse Cloud organization the API key is scoped to (the API returns exactly one organization per key).",+ "docs_url": "https://clickhouse.com/docs/cloud/manage/api/swagger",+ "columns": {+ "id": "Unique organization ID.",+ "createdAt": "The timestamp the organization was created. ISO-8601.",+ "name": "Name of the organization.",+ "privateEndpoints": "List of private endpoints for the organization.",+ "byocConfig": "BYOC (bring your own cloud) configuration for the organization.",+ "enableCoreDumps": "Whether crash report (core dump) collection is enabled for services in the organization.",+ },+ },+ "services": {+ "description": "All ClickHouse Cloud services in the organization, including state, tier, region, and scaling configuration.",+ "docs_url": "https://clickhouse.com/docs/cloud/manage/api/swagger",+ "columns": {+ "id": "Unique service ID.",+ "organizationId": "ID of the organization the service belongs to.",+ "name": "Name of the service.",+ "provider": "Cloud provider (aws, gcp, azure).",+ "region": "Service region.",+ "state": "Current state of the service.",+ "clickhouseVersion": "ClickHouse version of the service.",+ "endpoints": "List of all service endpoints.",+ "tier": "Deprecated service tier; use minReplicaMemoryGb, maxReplicaMemoryGb, and numReplicas instead.",+ "minReplicaMemoryGb": "Minimum total memory of each replica during auto-scaling, in GB.",+ "maxReplicaMemoryGb": "Maximum total memory of each replica during auto-scaling, in GB.",+ "numReplicas": "Number of replicas for the service.",+ "autoscalingMode": "Configured autoscaling mode: vertical (fixed replica count, memory scales) or horizontal (replica count scales at fixed memory).",+ "idleScaling": "When true the service is allowed to scale down to zero when idle.",+ "idleTimeoutMinutes": "Minimum idling timeout in minutes.",+ "ipAccessList": "List of IP addresses allowed to access the service.",+ "createdAt": "Service creation timestamp. ISO-8601.",+ "dataWarehouseId": "Data warehouse containing this service.",+ "isPrimary": "True if this service is the primary service in the data warehouse.",+ "isReadonly": "True if this service is read-only.",+ "releaseChannel": "Release channel of the service: fast, default, or slow.",+ "complianceType": "Type of regulatory compliance for the service.",+ "tags": "Tags associated with the service.",+ },+ },+ "usage_cost": {+ "description": "Daily per-entity usage cost records in ClickHouse Credits (CHCs), broken down by storage, compute, backup, and data transfer. Recent records may be restated until locked.",+ "docs_url": "https://clickhouse.com/docs/cloud/manage/api/swagger",+ "columns": {+ "organizationId": "ID of the organization the usage cost belongs to.",+ "date": "Date of the usage. ISO-8601 date, based on the UTC timezone.",+ "entityType": "Type of the entity: datawarehouse, service, or clickpipe.",+ "entityId": "Unique ID of the entity.",+ "entityName": "Name of the entity.",+ "dataWarehouseId": "ID of the data warehouse this entity belongs to (or is).",+ "serviceId": "ID of the service this entity belongs to (or is). Null for data warehouse entities.",+ "totalCHC": "Total cost of usage in ClickHouse Credits (CHCs) for this entity.",+ "locked": "When true, the record is immutable. Unlocked records are subject to change until locked.",+ "storageCHC": "Cost of storage in ClickHouse Credits (CHCs). Applies to data warehouse entities.",+ "backupCHC": "Cost of backup in ClickHouse Credits (CHCs). Applies to data warehouse entities.",+ "computeCHC": "Cost of compute in ClickHouse Credits (CHCs). Applies to service and ClickPipe entities.",+ "dataTransferCHC": "Cost of data transfer in ClickHouse Credits (CHCs). Applies to ClickPipe entities.",+ "initialLoadCHC": "Cost of initial load and resyncs in ClickHouse Credits (CHCs). Applies to ClickPipe entities.",+ "publicDataTransferCHC": "Cost of public data transfer in ClickHouse Credits (CHCs). Applies to service entities.",+ "interRegionTier1DataTransferCHC": "Cost of tier 1 inter-region data transfer in ClickHouse Credits (CHCs). Applies to service entities.",+ "interRegionTier2DataTransferCHC": "Cost of tier 2 inter-region data transfer in ClickHouse Credits (CHCs). Applies to service entities.",+ "interRegionTier3DataTransferCHC": "Cost of tier 3 inter-region data transfer in ClickHouse Credits (CHCs). Applies to service entities.",+ "interRegionTier4DataTransferCHC": "Cost of tier 4 inter-region data transfer in ClickHouse Credits (CHCs). Applies to service entities.",+ },+ },+ "api_keys": {+ "description": "All API keys in the organization (metadata only — the API never returns key secrets).",+ "docs_url": "https://clickhouse.com/docs/cloud/manage/api/swagger",+ "columns": {+ "id": "Unique API key ID.",+ "organizationId": "ID of the organization the key belongs to.",+ "name": "Name of the key.",+ "state": "State of the key: enabled or disabled.",+ "roles": "Deprecated list of roles assigned to the key; use assignedRoles instead.",+ "assignedRoles": "Custom roles and system roles assigned to this API key.",+ "keySuffix": "Last 4 letters of the key.",+ "createdAt": "Timestamp the key was created. ISO-8601.",+ "expireAt": "Timestamp the key expires. Null or empty if the key never expires. ISO-8601.",+ "usedAt": "Timestamp the key was last used. Absent if the key was never used. ISO-8601.",+ "ipAccessList": "List of IP addresses allowed to use this key.",+ },+ },+ "members": {+ "description": "All members of the organization and their roles.",+ "docs_url": "https://clickhouse.com/docs/cloud/manage/api/swagger",+ "columns": {+ "organizationId": "ID of the organization the member belongs to.",+ "userId": "Unique user ID, stable across organizations.",+ "name": "Name of the member as set in their personal user profile.",+ "email": "Email of the member as set in their personal user profile.",+ "role": "Deprecated role of the member in the organization; use assignedRoles instead.",+ "assignedRoles": "Custom roles and system roles assigned to this member.",+ "joinedAt": "Timestamp the member joined the organization. ISO-8601.",+ },+ },+ "activities": {+ "description": "The organization audit log: service, key, and member changes with actor details.",+ "docs_url": "https://clickhouse.com/docs/cloud/manage/api/swagger",+ "columns": {+ "id": "Unique activity ID.",+ "createdAt": "Timestamp of the activity. ISO-8601.",+ "type": "Type of the activity.",+ "actorType": "Type of the actor: user, support, system, or api.",+ "actorId": "Unique actor ID.",+ "actorDetails": "Additional information about the actor.",+ "actorIpAddress": "IP address of the actor. Defined for user and api actor types.",+ "organizationId": "Organization ID this activity is related to.",+ "serviceId": "Service ID this activity is related to.",+ "userAgent": "User agent of the actor.",+ "targetKeyId": "For openapi_key_update activities: the ID of the API key that was updated.",+ "keyUpdateType": "For openapi_key_update activities: the type of update that was performed.",+ },+ },+ "backups": {+ "description": "Backups for every service in the organization, most recent first.",+ "docs_url": "https://clickhouse.com/docs/cloud/manage/api/swagger",+ "columns": {+ "id": "Unique backup ID.",+ "organizationId": "ID of the organization the backup belongs to.",+ "serviceId": "ID of the service the backup belongs to.",+ "status": "Status of the backup: done, error, or in_progress.",+ "startedAt": "Backup start timestamp. ISO-8601.",+ "finishedAt": "Backup finish timestamp. ISO-8601. Available only for finished backups.",+ "sizeInBytes": "Size of the backup in bytes.",+ "durationInSeconds": "Time in seconds it took to perform the backup.",+ "type": "Backup type: full or incremental.",+ "backupName": "Backup name on the external backup bucket.",+ "bucket": "Backup bucket where the backup is stored.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/clickhouse_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/clickhouse_cloud.pynew file mode 100644index 000000000000..4beef1fec152--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/clickhouse_cloud.py@@ -0,0 +1,367 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse_cloud.settings import (+ CLICKHOUSE_CLOUD_ENDPOINTS,+ USAGE_COST_MAX_WINDOW_DAYS,+ ClickhouseCloudEndpointConfig,+)+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++CLICKHOUSE_CLOUD_BASE_URL = "https://api.clickhouse.cloud"+# Floor for a full-refresh usage_cost backfill when the organization's createdAt is missing —+# ClickHouse Cloud launched in late 2022, so no billing data can predate this.+DEFAULT_USAGE_COST_START = date(2022, 1, 1)+++class ClickhouseCloudRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ # Seconds the server asked us to wait (from a 429 `Retry-After`), or None to back off blindly.+ self.retry_after = retry_after+++# The API allows 10 requests per 10-second window per key, so 429s are expected on orgs with many+# services. Cap the honored `Retry-After` so a pathological header can't pin the worker.+_MAX_RETRY_AFTER_SECONDS = 60+_fallback_wait = wait_exponential_jitter(initial=2, max=30)+++def _parse_retry_after(value: str | None) -> float | None:+ """Parse a delta-seconds `Retry-After` header. Returns None for a missing, non-numeric, or+ negative value so the caller falls back to exponential backoff."""+ if value is None:+ return None+ try:+ seconds = float(value)+ except (TypeError, ValueError):+ return None+ return seconds if seconds >= 0 else None+++def _wait_clickhouse_cloud(retry_state: RetryCallState) -> float:+ """Honor the server's `Retry-After` on 429s (capped), else fall back to exponential jitter."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, ClickhouseCloudRetryableError) and exc.retry_after is not None:+ return min(exc.retry_after, _MAX_RETRY_AFTER_SECONDS)+ return _fallback_wait(retry_state)+++class ClickhouseCloudResumeConfig:+ # usage_cost only: the organization and window start (YYYY-MM-DD) to resume from. Every other+ # endpoint is a single unpaginated request per organization, so a retry just refetches it.+ organization_id: str | None = None+ from_date: str | None = None+++def _make_session(key_id: str, key_secret: str) -> requests.Session:+ session = make_tracked_session(headers={"Accept": "application/json"})+ # The Cloud API authenticates with HTTP Basic: key ID as username, key secret as password.+ session.auth = (key_id, key_secret)+ return session+++def _build_url(path: str, params: dict[str, Any] | None = None) -> str:+ url = f"{CLICKHOUSE_CLOUD_BASE_URL}{path}"+ if not params:+ return url+ return f"{url}?{urlencode({k: str(v) for k, v in params.items() if v is not None})}"+++@retry(+ retry=retry_if_exception_type(+ (+ ClickhouseCloudRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=_wait_clickhouse_cloud,+ reraise=True,+)+def _fetch(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict:+ response = session.get(url, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ retry_after = _parse_retry_after(response.headers.get("retry-after")) if response.status_code == 429 else None+ raise ClickhouseCloudRetryableError(+ f"ClickHouse Cloud API error (retryable): status={response.status_code}, url={url}",+ retry_after=retry_after,+ )++ if not response.ok:+ logger.error(f"ClickHouse Cloud API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(key_id: str, key_secret: str) -> bool:+ url = _build_url("/v1/organizations")+ try:+ response = _make_session(key_id, key_secret).get(url, timeout=10)+ except Exception:+ return False+ # 200 => valid. 403 => a real key without the scope we probed; accept it at create time+ # (sync-time 403s are caught by get_non_retryable_errors). 401 => bad key ID/secret.+ return response.status_code in (200, 403)+++def _coerce_date(value: Any) -> date | None:+ """Coerce a watermark or API value (date, datetime, or ISO string) to a date."""+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ if isinstance(value, str) and value:+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00")).date()+ except ValueError:+ return None+ return None+++def _format_rfc3339(value: Any) -> str:+ """Format a datetime/date as an RFC 3339 UTC timestamp with a Z suffix."""+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ elif isinstance(value, date):+ dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ else:+ return str(value)+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _list_organizations(session: requests.Session, logger: FilteringBoundLogger) -> list[dict[str, Any]]:+ data = _fetch(session, _build_url("/v1/organizations"), logger)+ return data.get("result") or []+++def _with_organization_id(item: dict[str, Any], organization_id: str) -> dict[str, Any]:+ """Stamp the parent organization onto a row so composite primary keys are always populated.+ Rows that already carry organizationId (activities) keep their own value."""+ if item.get("organizationId"):+ return item+ return {**item, "organizationId": organization_id}+++def _iter_entity_rows(+ session: requests.Session,+ logger: FilteringBoundLogger,+ config: ClickhouseCloudEndpointConfig,+ organizations: list[dict[str, Any]],+) -> Iterator[list[dict[str, Any]]]:+ for org in organizations:+ url = _build_url(config.path.format(organization_id=org["id"]))+ result = _fetch(session, url, logger).get("result") or []+ rows = [_with_organization_id(item, org["id"]) for item in result]+ if rows:+ yield rows+++def _iter_activity_rows(+ session: requests.Session,+ logger: FilteringBoundLogger,+ config: ClickhouseCloudEndpointConfig,+ organizations: list[dict[str, Any]],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ params: dict[str, Any] = {}+ if should_use_incremental_field and db_incremental_field_last_value:+ params["from_date"] = _format_rfc3339(db_incremental_field_last_value)++ for org in organizations:+ url = _build_url(config.path.format(organization_id=org["id"]), params)+ result = _fetch(session, url, logger).get("result") or []+ rows = [_with_organization_id(item, org["id"]) for item in result]+ # The API doesn't document response ordering; sort ascending client-side (the full array is+ # already in memory) so the pipeline's per-batch watermark checkpoints stay correct.+ rows.sort(key=lambda row: str(row.get("createdAt") or ""))+ if rows:+ yield rows+++def _iter_backup_rows(+ session: requests.Session,+ logger: FilteringBoundLogger,+ config: ClickhouseCloudEndpointConfig,+ organizations: list[dict[str, Any]],+) -> Iterator[list[dict[str, Any]]]:+ for org in organizations:+ services_url = _build_url(f"/v1/organizations/{org['id']}/services")+ services = _fetch(session, services_url, logger).get("result") or []+ for service in services:+ url = _build_url(config.path.format(organization_id=org["id"], service_id=service["id"]))+ result = _fetch(session, url, logger).get("result") or []+ rows = [+ {**_with_organization_id(item, org["id"]), "serviceId": item.get("serviceId") or service["id"]}+ for item in result+ ]+ if rows:+ yield rows+++def _flatten_usage_cost_record(record: dict[str, Any], organization_id: str) -> dict[str, Any]:+ """Surface the nested per-record `metrics` object (storageCHC, computeCHC, ...) as flat columns+ so cost dashboards can query them directly. The metric keys are all distinct from the record's+ own fields, so flattening can't collide."""+ metrics = record.get("metrics") or {}+ row = {key: value for key, value in record.items() if key != "metrics"}+ row.update(metrics)+ row["organizationId"] = organization_id+ return row+++def _usage_cost_start(+ org: dict[str, Any],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> date:+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ coerced = _coerce_date(db_incremental_field_last_value)+ if coerced is not None:+ return coerced+ # Full refresh / first sync: pull all available history from the organization's creation date.+ return _coerce_date(org.get("createdAt")) or DEFAULT_USAGE_COST_START+++def _iter_usage_cost_rows(+ session: requests.Session,+ logger: FilteringBoundLogger,+ config: ClickhouseCloudEndpointConfig,+ organizations: list[dict[str, Any]],+ resumable_source_manager: ResumableSourceManager[ClickhouseCloudResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ """Walk usageCost forward in windows of at most 31 days (the API's per-request cap) up to today.++ Windows never overlap (next start = previous end + 1 day, to_date is inclusive), so a single+ sync can't yield duplicate rows. The resume bookmark points at the next window start and is+ saved only AFTER the preceding window's rows are yielded — a crash re-pulls the last window and+ merge dedupes it on the primary key.+ """+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ today = datetime.now(UTC).date()++ for org in organizations:+ start = _usage_cost_start(org, should_use_incremental_field, db_incremental_field_last_value)+ if resume is not None and resume.organization_id == org["id"] and resume.from_date:+ start = date.fromisoformat(resume.from_date)+ logger.debug(f"ClickHouse Cloud: resuming usage_cost from {start.isoformat()}")+ # A future-dated watermark (clock skew, bad data) would make from_date > to_date and 400.+ start = min(start, today)++ while True:+ window_end = min(start + timedelta(days=USAGE_COST_MAX_WINDOW_DAYS - 1), today)+ url = _build_url(+ config.path.format(organization_id=org["id"]),+ {"from_date": start.isoformat(), "to_date": window_end.isoformat()},+ )+ result = _fetch(session, url, logger).get("result") or {}+ records = result.get("costs") or []+ rows = [_flatten_usage_cost_record(record, org["id"]) for record in records]+ # Records within a window aren't ordered; sort so dates ascend across the whole run and+ # the pipeline's per-batch watermark checkpoints stay correct.+ rows.sort(key=lambda row: str(row.get("date") or ""))+ if rows:+ yield rows++ if window_end >= today:+ break+ next_start = window_end + timedelta(days=1)+ resumable_source_manager.save_state(+ ClickhouseCloudResumeConfig(organization_id=org["id"], from_date=next_start.isoformat())+ )+ start = next_start+++def get_rows(+ key_id: str,+ key_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ClickhouseCloudResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = CLICKHOUSE_CLOUD_ENDPOINTS[endpoint]+ session = _make_session(key_id, key_secret)++ organizations = _list_organizations(session, logger)+ if endpoint == "organizations":+ if organizations:+ yield organizations+ return++ if endpoint == "usage_cost":+ yield from _iter_usage_cost_rows(+ session,+ logger,+ config,+ organizations,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ elif endpoint == "activities":+ yield from _iter_activity_rows(+ session,+ logger,+ config,+ organizations,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ elif config.fan_out_over_services:+ yield from _iter_backup_rows(session, logger, config, organizations)+ else:+ yield from _iter_entity_rows(session, logger, config, organizations)+++def clickhouse_cloud_source(+ key_id: str,+ key_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ClickhouseCloudResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = CLICKHOUSE_CLOUD_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ key_id=key_id,+ key_secret=key_secret,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ # An API key is scoped to exactly one organization (the API documents this), usage_cost+ # windows advance forward, and activities are sorted client-side — so incremental rows+ # arrive in ascending order and the pipeline can checkpoint the watermark per batch.+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/settings.pynew file mode 100644index 000000000000..c19226db567d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/settings.py@@ -0,0 +1,118 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# usageCost windows span at most 31 days per request (from_date..to_date, both inclusive).+USAGE_COST_MAX_WINDOW_DAYS = 31++# Recent usage cost records are restated until ClickHouse locks them (the API marks them+# `locked=false`, "subject to change until locked"). The lock cadence is undocumented, so re-pull a+# full billing month on every incremental run; merge dedupes the overlap on the primary key and the+# extra window costs at most one additional request per sync.+USAGE_COST_LOOKBACK_SECONDS = 60 * 60 * 24 * 31+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++def _date_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.Date,+ "field": name,+ "field_type": IncrementalFieldType.Date,+ }+++@dataclass+class ClickhouseCloudEndpointConfig:+ name: str+ # Path relative to the API host, with {organization_id} / {service_id} placeholders.+ path: str+ primary_keys: list[str]+ # Stable creation-style field used for datetime partitioning — never an updated-style field.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Only True where the API exposes a genuine server-side time filter: usageCost's required+ # from_date/to_date window and activities' optional from_date. Every other endpoint returns a+ # complete unfiltered array, so those are full-refresh only.+ supports_incremental: bool = False+ # usage_cost records get restated until locked and activities' server-side filter is documented+ # but not verifiable without live credentials, so both incremental endpoints are merge-only —+ # append would materialize re-pulled rows as duplicates.+ supports_append: bool = False+ # backups has no org-wide list endpoint; it fans out one request per service.+ fan_out_over_services: bool = False+ should_sync_default: bool = True+ # Re-read window (seconds) the pipeline subtracts from the incremental watermark before it+ # reaches the source, so each run re-pulls recently-restated records.+ default_incremental_lookback_seconds: Optional[int] = None+ description: Optional[str] = None+++CLICKHOUSE_CLOUD_ENDPOINTS: dict[str, ClickhouseCloudEndpointConfig] = {+ "organizations": ClickhouseCloudEndpointConfig(+ name="organizations",+ path="/v1/organizations",+ primary_keys=["id"],+ description="The organization the API key is scoped to (the API returns exactly one).",+ ),+ "services": ClickhouseCloudEndpointConfig(+ name="services",+ path="/v1/organizations/{organization_id}/services",+ primary_keys=["organizationId", "id"],+ description="All ClickHouse Cloud services in the organization, including state, tier, region, and scaling configuration.",+ ),+ "usage_cost": ClickhouseCloudEndpointConfig(+ name="usage_cost",+ path="/v1/organizations/{organization_id}/usageCost",+ primary_keys=["organizationId", "date", "entityId"],+ partition_key="date",+ supports_incremental=True,+ incremental_fields=[_date_incremental_field("date")],+ default_incremental_lookback_seconds=USAGE_COST_LOOKBACK_SECONDS,+ description="Daily per-entity usage cost records in ClickHouse Credits (CHCs), broken down by storage, compute, backup, and data transfer.",+ ),+ "api_keys": ClickhouseCloudEndpointConfig(+ name="api_keys",+ path="/v1/organizations/{organization_id}/keys",+ primary_keys=["organizationId", "id"],+ description="All API keys in the organization (metadata only — the API never returns key secrets).",+ ),+ "members": ClickhouseCloudEndpointConfig(+ name="members",+ path="/v1/organizations/{organization_id}/members",+ primary_keys=["organizationId", "userId"],+ description="All members of the organization and their roles.",+ ),+ "activities": ClickhouseCloudEndpointConfig(+ name="activities",+ path="/v1/organizations/{organization_id}/activities",+ primary_keys=["organizationId", "id"],+ partition_key="createdAt",+ supports_incremental=True,+ incremental_fields=[_datetime_incremental_field("createdAt")],+ description="The organization audit log: service, key, and member changes with actor details.",+ ),+ "backups": ClickhouseCloudEndpointConfig(+ name="backups",+ path="/v1/organizations/{organization_id}/services/{service_id}/backups",+ primary_keys=["organizationId", "serviceId", "id"],+ partition_key="startedAt",+ fan_out_over_services=True,+ description="Backups for every service in the organization (one API request per service).",+ ),+}++ENDPOINTS = tuple(CLICKHOUSE_CLOUD_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CLICKHOUSE_CLOUD_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/source.pyindex dd8e56f678a3..332e20195e09 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/source.py@@ -1,13 +1,35 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse_cloud.clickhouse_cloud import (+ ClickhouseCloudResumeConfig,+ clickhouse_cloud_source,+ validate_credentials as validate_clickhouse_cloud_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse_cloud.settings import (+ CLICKHOUSE_CLOUD_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (ClickhouseCloudSourceConfig,)@@ -15,7 +37,9 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ClickhouseCloudSource(SimpleSource[ClickhouseCloudSourceConfig]):+class ClickhouseCloudSource(ResumableSource[ClickhouseCloudSourceConfig, ClickhouseCloudResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CLICKHOUSECLOUD@@ -26,7 +50,100 @@ class ClickhouseCloudSource(SimpleSource[ClickhouseCloudSourceConfig]):name=SchemaExternalDataSourceType.CLICKHOUSE_CLOUD,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="ClickHouse Cloud (ClickHouse, Inc.)",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your ClickHouse Cloud API key to pull your organization's usage costs, service inventory, and audit log into the PostHog Data warehouse.++Generate an API key from your [ClickHouse Cloud console](https://console.clickhouse.cloud/) under your organization's **API keys** settings. Keys with the **Admin** role can read every table; a **Developer**-scoped key may not have access to the usage cost and audit log tables.""",iconPath="/static/services/clickhouse_cloud.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/clickhouse-cloud",+ keywords=["clickhouse", "cloud costs", "finops", "billing"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="key_id",+ label="API key ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="key_secret",+ label="API key secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse_cloud.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.clickhouse.cloud": "Your ClickHouse Cloud API key is invalid or has been revoked. Generate a new API key in the ClickHouse Cloud console, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.clickhouse.cloud": "Your ClickHouse Cloud API key does not have permission to read this data. Use a key with the Admin role, then reconnect.",+ }++ def get_schemas(+ self,+ config: ClickhouseCloudSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = CLICKHOUSE_CLOUD_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_append,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,+ description=endpoint_config.description,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: ClickhouseCloudSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_clickhouse_cloud_credentials(config.key_id, config.key_secret):+ return True, None++ return False, "Invalid ClickHouse Cloud API key ID or secret"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ClickhouseCloudResumeConfig]:+ return ResumableSourceManager[ClickhouseCloudResumeConfig](inputs, ClickhouseCloudResumeConfig)++ def source_for_pipeline(+ self,+ config: ClickhouseCloudSourceConfig,+ resumable_source_manager: ResumableSourceManager[ClickhouseCloudResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return clickhouse_cloud_source(+ key_id=config.key_id,+ key_secret=config.key_secret,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/tests/test_clickhouse_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/tests/test_clickhouse_cloud.pynew file mode 100644index 000000000000..fe1f6a0e811f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/tests/test_clickhouse_cloud.py@@ -0,0 +1,338 @@+from datetime import UTC, date, datetime, timedelta+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse_cloud import clickhouse_cloud+from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse_cloud.clickhouse_cloud import (+ ClickhouseCloudResumeConfig,+ _coerce_date,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse_cloud.source import (+ ClickhouseCloudSource,+)++ORG = {"id": "org-1", "createdAt": "2026-05-01T10:00:00Z", "name": "Acme"}+++class _FakeResumableManager:+ def __init__(self, state: ClickhouseCloudResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[ClickhouseCloudResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> ClickhouseCloudResumeConfig | None:+ return self._state++ def save_state(self, data: ClickhouseCloudResumeConfig) -> None:+ self.saved.append(data)+++def _collect(+ monkeypatch: Any,+ handler: Any,+ endpoint: str,+ manager: _FakeResumableManager | None = None,+ **kw: Any,+) -> tuple[list[dict], list[str]]:+ calls: list[str] = []++ def fake_fetch(session: Any, url: str, logger: Any) -> dict:+ calls.append(url)+ return handler(url)++ monkeypatch.setattr(clickhouse_cloud, "_fetch", fake_fetch)+ monkeypatch.setattr(clickhouse_cloud, "make_tracked_session", lambda **_: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ key_id="test-key-id",+ key_secret="test-key-secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager or _FakeResumableManager(), # type: ignore[arg-type]+ **kw,+ ):+ rows.extend(batch)+ return rows, calls+++def _usage_cost_handler(records_by_from_date: dict[str, list[dict]] | None = None) -> Any:+ def handler(url: str) -> dict:+ if url.endswith("/v1/organizations"):+ return {"result": [ORG]}+ params = parse_qs(urlparse(url).query)+ from_date = params["from_date"][0]+ records = (records_by_from_date or {}).get(from_date, [])+ return {"result": {"grandTotalCHC": 0, "costs": records}}++ return handler+++def _window_params(calls: list[str]) -> list[tuple[date, date]]:+ windows = []+ for url in calls:+ if "usageCost" not in url:+ continue+ params = parse_qs(urlparse(url).query)+ windows.append((date.fromisoformat(params["from_date"][0]), date.fromisoformat(params["to_date"][0])))+ return windows+++@freeze_time("2026-07-15")+class TestUsageCostWindowing:+ def test_full_refresh_windows_are_contiguous_and_capped_at_31_days(self, monkeypatch: Any) -> None:+ # A window longer than 31 days is rejected by the API with a 400, and overlapping windows+ # would yield duplicate rows within a single sync (merge only dedupes across syncs).+ _, calls = _collect(monkeypatch, _usage_cost_handler(), "usage_cost")+ windows = _window_params(calls)++ assert windows[0][0] == date(2026, 5, 1) # starts at the org's createdAt+ assert windows[-1][1] == date(2026, 7, 15) # walks all the way to today+ for from_date, to_date in windows:+ assert (to_date - from_date).days <= 30 # to_date is inclusive => at most 31 days+ for previous, current in zip(windows, windows[1:]):+ assert (current[0] - previous[1]).days == 1 # contiguous, no overlap, no gap++ def test_incremental_starts_from_watermark(self, monkeypatch: Any) -> None:+ _, calls = _collect(+ monkeypatch,+ _usage_cost_handler(),+ "usage_cost",+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 7, 1),+ )+ windows = _window_params(calls)+ assert windows == [(date(2026, 7, 1), date(2026, 7, 15))]++ def test_future_watermark_is_clamped_to_today(self, monkeypatch: Any) -> None:+ # A future-dated watermark would make from_date > to_date and 400 on every sync.+ _, calls = _collect(+ monkeypatch,+ _usage_cost_handler(),+ "usage_cost",+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 8, 1),+ )+ windows = _window_params(calls)+ assert windows == [(date(2026, 7, 15), date(2026, 7, 15))]++ def test_resume_state_used_and_saved_only_after_yield(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(ClickhouseCloudResumeConfig(organization_id="org-1", from_date="2026-06-20"))+ _, calls = _collect(monkeypatch, _usage_cost_handler(), "usage_cost", manager=manager)+ windows = _window_params(calls)++ assert windows[0][0] == date(2026, 6, 20) # resumed from the bookmark, not createdAt+ # One bookmark per completed non-final window, each pointing at the next window start —+ # a crash re-pulls the last yielded window rather than skipping ahead.+ assert len(manager.saved) == len(windows) - 1+ for saved, (_, window_end), (next_start, _) in zip(manager.saved, windows, windows[1:]):+ assert saved.organization_id == "org-1"+ assert saved.from_date == next_start.isoformat()+ assert next_start == window_end + timedelta(days=1)++ def test_rows_flatten_metrics_and_stamp_organization_id(self, monkeypatch: Any) -> None:+ records = [+ {+ "date": "2026-07-02",+ "entityType": "service",+ "entityId": "svc-1",+ "metrics": {"computeCHC": 1.5, "storageCHC": 0.25},+ "totalCHC": 1.75,+ },+ {"date": "2026-07-01", "entityType": "datawarehouse", "entityId": "dw-1", "totalCHC": 0.5},+ ]+ rows, _ = _collect(+ monkeypatch,+ _usage_cost_handler({"2026-07-01": records}),+ "usage_cost",+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 7, 1),+ )+ # Sorted ascending by date so the pipeline's per-batch watermark stays correct.+ assert [r["date"] for r in rows] == ["2026-07-01", "2026-07-02"]+ service_row = rows[1]+ assert service_row["computeCHC"] == 1.5+ assert service_row["storageCHC"] == 0.25+ assert "metrics" not in service_row+ assert all(r["organizationId"] == "org-1" for r in rows)+++class TestActivities:+ def test_incremental_passes_from_date_and_sorts_ascending(self, monkeypatch: Any) -> None:+ activities = [+ {"id": "a-2", "createdAt": "2026-07-02T00:00:00Z", "organizationId": "org-1"},+ {"id": "a-1", "createdAt": "2026-07-01T00:00:00Z", "organizationId": "org-1"},+ ]++ def handler(url: str) -> dict:+ if url.endswith("/v1/organizations"):+ return {"result": [ORG]}+ return {"result": activities}++ rows, calls = _collect(+ monkeypatch,+ handler,+ "activities",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 30, tzinfo=UTC),+ )+ assert "from_date=2026-06-30T00%3A00%3A00Z" in calls[1]+ assert [r["id"] for r in rows] == ["a-1", "a-2"]++ def test_full_refresh_omits_from_date(self, monkeypatch: Any) -> None:+ def handler(url: str) -> dict:+ if url.endswith("/v1/organizations"):+ return {"result": [ORG]}+ return {"result": []}++ _, calls = _collect(monkeypatch, handler, "activities")+ assert "from_date" not in calls[1]+++class TestEntityRows:+ def test_organizations_endpoint_yields_org_rows(self, monkeypatch: Any) -> None:+ rows, calls = _collect(monkeypatch, lambda url: {"result": [ORG]}, "organizations")+ assert rows == [ORG]+ assert len(calls) == 1++ @parameterized.expand([("services", "/services"), ("api_keys", "/keys"), ("members", "/members")])+ def test_org_id_stamped_onto_child_rows(self, endpoint: str, path_suffix: str) -> None:+ # The composite primary keys ([organizationId, ...]) require every row to carry the parent+ # organization; the API omits it from these list responses.+ def handler(url: str) -> dict:+ if url.endswith("/v1/organizations"):+ return {"result": [ORG]}+ assert url.endswith(path_suffix)+ return {"result": [{"id": "child-1", "userId": "user-1"}]}++ with patch.object(clickhouse_cloud, "make_tracked_session", return_value=MagicMock()):+ with patch.object(clickhouse_cloud, "_fetch", side_effect=lambda _session, url, _logger: handler(url)):+ rows: list[dict] = []+ for batch in get_rows("k", "s", endpoint, MagicMock(), _FakeResumableManager()): # type: ignore[arg-type]+ rows.extend(batch)+ assert rows[0]["organizationId"] == "org-1"+++class TestBackupsFanOut:+ def test_one_request_per_service_with_ids_stamped(self, monkeypatch: Any) -> None:+ def handler(url: str) -> dict:+ if url.endswith("/v1/organizations"):+ return {"result": [ORG]}+ if url.endswith("/services"):+ return {"result": [{"id": "svc-1"}, {"id": "svc-2"}]}+ if url.endswith("/services/svc-1/backups"):+ return {"result": [{"id": "b-1", "status": "done"}]}+ if url.endswith("/services/svc-2/backups"):+ return {"result": [{"id": "b-2", "status": "done"}]}+ raise AssertionError(f"unexpected url: {url}")++ rows, calls = _collect(monkeypatch, handler, "backups")+ assert [(r["organizationId"], r["serviceId"], r["id"]) for r in rows] == [+ ("org-1", "svc-1", "b-1"),+ ("org-1", "svc-2", "b-2"),+ ]+ assert sum("backups" in url for url in calls) == 2+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("forbidden_scope", 403, True), ("unauthorized", 401, False)])+ def test_status_mapping(self, _name: str, status: int, expected: bool) -> None:+ # 403 is accepted at create time (real key, unprobed scope); 401 means a bad key ID/secret.+ response = MagicMock(status_code=status)+ session = MagicMock()+ session.get.return_value = response+ with patch.object(clickhouse_cloud, "make_tracked_session", return_value=session):+ assert validate_credentials("key-id", "key-secret") is expected++ def test_network_error_is_invalid(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(clickhouse_cloud, "make_tracked_session", return_value=session):+ assert validate_credentials("key-id", "key-secret") is False+++class TestFetch:+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])+ def test_retryable_statuses_exhaust_retry_budget(self, _name: str, status: int) -> None:+ response = MagicMock(status_code=status, ok=False, headers={})+ session = MagicMock()+ session.get.return_value = response+ with patch.object(clickhouse_cloud._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(clickhouse_cloud.ClickhouseCloudRetryableError):+ clickhouse_cloud._fetch(session, "https://api.clickhouse.cloud/v1/organizations", MagicMock())+ assert session.get.call_count == 5++ def test_client_error_raises_for_status_without_retry(self) -> None:+ response = MagicMock(status_code=401, ok=False, text="unauthorized")+ response.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=response)+ session = MagicMock()+ session.get.return_value = response+ with pytest.raises(requests.HTTPError):+ clickhouse_cloud._fetch(session, "https://api.clickhouse.cloud/v1/organizations", MagicMock())+ assert session.get.call_count == 1++ def test_429_honors_retry_after_header(self) -> None:+ # The API allows 10 requests per 10s, so 429s are routine — honoring the server's window+ # beats blind backoff; the cap stops a pathological header from wedging the worker.+ response = MagicMock(status_code=429, ok=False, headers={"retry-after": "7"})+ session = MagicMock()+ session.get.return_value = response+ with patch.object(clickhouse_cloud._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(clickhouse_cloud.ClickhouseCloudRetryableError) as exc_info:+ clickhouse_cloud._fetch(session, "https://api.clickhouse.cloud/v1/organizations", MagicMock())+ assert exc_info.value.retry_after == 7.0+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.clickhouse.cloud/v1/organizations"),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.clickhouse.cloud/v1/organizations/org-1/usageCost?from_date=2026-07-01&to_date=2026-07-15",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = ClickhouseCloudSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='api.clickhouse.cloud', port=443): Read timed out."),+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.clickhouse.cloud/v1/organizations",+ ),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = ClickhouseCloudSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestCoerceDate:+ @parameterized.expand(+ [+ ("date", date(2026, 7, 1), date(2026, 7, 1)),+ ("datetime", datetime(2026, 7, 1, 12, 30, tzinfo=UTC), date(2026, 7, 1)),+ ("iso_date_string", "2026-07-01", date(2026, 7, 1)),+ ("iso_datetime_z_string", "2026-07-01T10:00:00Z", date(2026, 7, 1)),+ ("garbage_string", "not-a-date", None),+ ("empty_string", "", None),+ ("none", None, None),+ ]+ )+ def test_coercion(self, _name: str, value: Any, expected: date | None) -> None:+ assert _coerce_date(value) == expecteddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/tests/test_clickhouse_cloud_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/tests/test_clickhouse_cloud_source.pynew file mode 100644index 000000000000..04791d25f06c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/tests/test_clickhouse_cloud_source.py@@ -0,0 +1,138 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,+ SourceFieldInputConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse_cloud.clickhouse_cloud import (+ ClickhouseCloudResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse_cloud.settings import (+ USAGE_COST_LOOKBACK_SECONDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse_cloud.source import (+ ClickhouseCloudSource,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestClickhouseCloudSourceConfig:+ def test_source_type(self) -> None:+ assert ClickhouseCloudSource().source_type == ExternalDataSourceType.CLICKHOUSECLOUD++ def test_config_exposes_key_id_and_secret_fields(self) -> None:+ config = ClickhouseCloudSource().get_source_config+ assert config.name == SchemaExternalDataSourceType.CLICKHOUSE_CLOUD+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/clickhouse-cloud"+ assert config.unreleasedSource is None+ fields = [f for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert [f.name for f in fields] == ["key_id", "key_secret"]+ by_name = {f.name: f for f in fields}+ assert by_name["key_id"].secret is False and by_name["key_id"].required is True+ assert by_name["key_secret"].secret is True and by_name["key_secret"].required is True+++class TestClickhouseCloudSchemas:+ def test_all_endpoints_present(self) -> None:+ names = {s.name for s in ClickhouseCloudSource().get_schemas(MagicMock(), team_id=1)}+ assert names == {+ "organizations",+ "services",+ "usage_cost",+ "api_keys",+ "members",+ "activities",+ "backups",+ }++ def test_usage_cost_is_incremental_on_date_with_restatement_lookback(self) -> None:+ schema = next(s for s in ClickhouseCloudSource().get_schemas(MagicMock(), team_id=1) if s.name == "usage_cost")+ assert schema.supports_incremental is True+ assert schema.supports_append is False # unlocked records get restated; append would duplicate+ assert [f["field"] for f in schema.incremental_fields] == ["date"]+ assert schema.default_incremental_lookback_seconds == USAGE_COST_LOOKBACK_SECONDS++ def test_activities_is_incremental_on_created_at(self) -> None:+ schema = next(s for s in ClickhouseCloudSource().get_schemas(MagicMock(), team_id=1) if s.name == "activities")+ assert schema.supports_incremental is True+ assert schema.supports_append is False+ assert [f["field"] for f in schema.incremental_fields] == ["createdAt"]++ @parameterized.expand([("organizations",), ("services",), ("api_keys",), ("members",), ("backups",)])+ def test_snapshot_endpoints_are_full_refresh_only(self, endpoint: str) -> None:+ # These list endpoints return complete unfiltered arrays — no server-side updated-since+ # filter exists, so they must not advertise incremental.+ schema = next(s for s in ClickhouseCloudSource().get_schemas(MagicMock(), team_id=1) if s.name == endpoint)+ assert schema.supports_incremental is False+ assert schema.supports_append is False++ def test_names_filter(self) -> None:+ schemas = ClickhouseCloudSource().get_schemas(MagicMock(), team_id=1, names=["usage_cost"])+ assert [s.name for s in schemas] == ["usage_cost"]+++class TestValidateCredentials:+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])+ def test_plumbs_transport_result(self, _name: str, transport_result: bool, expected: bool) -> None:+ config = MagicMock(key_id="key-id", key_secret="key-secret")+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse_cloud.source.validate_clickhouse_cloud_credentials",+ return_value=transport_result,+ ) as mock_validate:+ ok, error = ClickhouseCloudSource().validate_credentials(config, team_id=1)+ assert ok is expected+ assert (error is None) is expected+ mock_validate.assert_called_once_with("key-id", "key-secret")+++class TestClickhouseCloudResumableManager:+ def test_manager_bound_to_resume_config(self) -> None:+ manager = ClickhouseCloudSource().get_resumable_source_manager(MagicMock())+ assert manager._data_class is ClickhouseCloudResumeConfig+++class TestClickhouseCloudSourceForPipeline:+ def _response(self, endpoint: str) -> object:+ inputs = MagicMock()+ inputs.schema_name = endpoint+ inputs.logger = MagicMock()+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = None+ config = MagicMock(key_id="key-id", key_secret="key-secret")+ return ClickhouseCloudSource().source_for_pipeline(config, MagicMock(), inputs)++ @parameterized.expand(+ [+ ("organizations", ["id"], None),+ ("services", ["organizationId", "id"], None),+ ("usage_cost", ["organizationId", "date", "entityId"], "datetime"),+ ("members", ["organizationId", "userId"], None),+ ("activities", ["organizationId", "id"], "datetime"),+ ("backups", ["organizationId", "serviceId", "id"], "datetime"),+ ]+ )+ def test_primary_keys_and_partitioning(+ self, endpoint: str, primary_keys: list[str], partition_mode: str | None+ ) -> None:+ response = self._response(endpoint)+ assert response.name == endpoint # type: ignore[attr-defined]+ assert response.primary_keys == primary_keys # type: ignore[attr-defined]+ assert response.sort_mode == "asc" # type: ignore[attr-defined]+ assert response.partition_mode == partition_mode # type: ignore[attr-defined]+++class TestDocumentedTables:+ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog => the source opts into publishing its table list to public docs.+ assert ClickhouseCloudSource().lists_tables_without_credentials is True+ tables = ClickhouseCloudSource().get_documented_tables()+ names = {t["name"] for t in tables}+ assert "usage_cost" in names and "services" in names+ usage = next(t for t in tables if t["name"] == "usage_cost")+ assert "Incremental" in usage["sync_methods"]+ assert usage["description"]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.pyindex 18097cea8378..11e66715e0e2 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@@ -931,7 +931,8 @@ class ClickUpSourceConfig(config.Config):@config.configclass ClickhouseCloudSourceConfig(config.Config):- pass+ key_id: str+ key_secret: str@config.config