: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 confluent_cloud import source (#71225)
Tom Owers651a376424d7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 91acf4c97456..90da940d0b2c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -132,6 +132,7 @@ the row lists both.| concord | HTTP | requests | ✅ || configcat | HTTP | requests | ✅ || confluence | HTTP | requests | ✅ |+| confluent_cloud | HTTP | requests | ✅ || chartmogul | HTTP | requests | ✅ || circleci | HTTP | requests | ✅ || cimis | HTTP | requests | ✅ |@@ -641,7 +642,6 @@ doesn't conflict with concurrent PRs.- cockroachdb- codacy- codecov-- confluent_cloud- constant_contact- copper- coralogixdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/canonical_descriptions.pynew file mode 100644index 000000000000..4e4e9abe16df--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/canonical_descriptions.py@@ -0,0 +1,57 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+ CanonicalEndpoint,+)++_METRICS_DOCS_URL = "https://api.telemetry.confluent.cloud/docs"++_TIME_SERIES_COLUMNS = {+ "metric": "Fully qualified metric name, e.g. io.confluent.kafka.server/received_bytes. The metric_descriptors table describes each one.",+ "resource_id": "ID of the Confluent Cloud resource the value belongs to, e.g. a Kafka cluster ID (lkc-...).",+ "timestamp": "Start of the UTC-aligned hourly bucket the value was aggregated for.",+ "value": "Aggregated metric value for the bucket, in the unit declared by the metric's descriptor.",+}+++def _time_series_table(resource_noun: str) -> CanonicalEndpoint:+ return {+ "description": f"Hourly time-series values for every Metrics API metric that applies to your {resource_noun}, one row per metric, resource, and hour.",+ "docs_url": _METRICS_DOCS_URL,+ "columns": _TIME_SERIES_COLUMNS,+ }+++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "metric_descriptors": {+ "description": "Metadata catalog for every metric available in the Metrics API 'cloud' dataset, including its data type, unit, and lifecycle stage.",+ "docs_url": _METRICS_DOCS_URL,+ "columns": {+ "name": "Fully qualified metric name, e.g. io.confluent.kafka.server/received_bytes.",+ "description": "Human-readable explanation of what the metric measures and how it is sampled.",+ "type": "Metric data type, e.g. GAUGE_INT64, GAUGE_DOUBLE, or COUNTER_INT64.",+ "unit": "Unit of the metric values, e.g. By (bytes) or 1 (dimensionless count).",+ "lifecycle_stage": "Release stage of the metric: GENERAL_AVAILABILITY, PREVIEW, or DEPRECATED.",+ "exportable": "Whether the metric is available from the Prometheus-format /export endpoint.",+ "resources": "Resource types the metric applies to, e.g. kafka, connector, compute_pool.",+ "labels": "Label keys the metric can be filtered or grouped by, e.g. the Kafka topic.",+ },+ },+ "resource_descriptors": {+ "description": "Metadata catalog for the resource types that metrics can be scoped to, such as Kafka clusters, connectors, and Flink compute pools.",+ "docs_url": _METRICS_DOCS_URL,+ "columns": {+ "type": "Resource type identifier, e.g. kafka, connector, ksql, schema_registry, compute_pool.",+ "description": "Human-readable description of the resource type.",+ "labels": "Label keys available for the resource, e.g. kafka.id and kafka.name.",+ },+ },+ "kafka_metrics": _time_series_table(+ "Kafka clusters (throughput, connections, partition counts, consumer lag, and more)"+ ),+ "connector_metrics": _time_series_table(+ "managed connectors (records and bytes moved, dead-letter queue activity, task statuses)"+ ),+ "ksqldb_metrics": _time_series_table("ksqlDB applications (streaming units, query saturation, processing errors)"),+ "schema_registry_metrics": _time_series_table("Schema Registry clusters (schema counts, request rates)"),+ "compute_pool_metrics": _time_series_table("Flink compute pools (CFU utilization and limits, statement metrics)"),+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/confluent_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/confluent_cloud.pynew file mode 100644index 000000000000..197fc242a278--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/confluent_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 retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.confluent_cloud.settings import (+ CONFLUENT_CLOUD_BASE_URL,+ CONFLUENT_CLOUD_ENDPOINTS,+ DATASET,+ DEFAULT_LOOKBACK_DAYS,+ DESCRIPTOR_PAGE_SIZE,+ GRANULARITY,+ INCREMENTAL_OVERLAP,+ QUERY_GROUP_LIMIT,+ QUERY_WINDOW,+)+++class ConfluentCloudRetryableError(Exception):+ pass+++class MissingResourceIdsError(Exception):+ pass+++class ConfluentCloudResumeConfig:+ # ISO-8601 start of the next day-window still to query. None means "start from the beginning+ # of the sync range". Only whole windows are checkpointed — page cursors are short-lived, so a+ # retried window always restarts fresh and merge dedupes the re-pulled rows.+ window_start: str | None = None+++def parse_resource_ids(raw: str | None) -> list[str]:+ """Split a comma/whitespace-separated resource id list into clean ids, preserving order."""+ if not raw:+ return []+ seen: set[str] = set()+ ids: list[str] = []+ for part in raw.replace(",", " ").split():+ if part not in seen:+ seen.add(part)+ ids.append(part)+ return ids+++def _make_session(api_key: str, api_secret: str) -> requests.Session:+ session = make_tracked_session(headers={"Accept": "application/json"})+ # The Metrics API authenticates with HTTP Basic auth: Cloud API key id as the username, the+ # secret as the password.+ session.auth = (api_key, api_secret)+ return session+++def _format_timestamp(dt: datetime) -> str:+ aware = dt if dt.tzinfo is not None else dt.replace(tzinfo=UTC)+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _coerce_datetime(value: Any) -> datetime | None:+ if isinstance(value, datetime):+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if isinstance(value, str):+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+ return None+++@retry(+ retry=retry_if_exception_type((ConfluentCloudRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+)+def _fetch_json(+ session: requests.Session,+ method: str,+ url: str,+ logger: FilteringBoundLogger,+ json_body: dict[str, Any] | None = None,+ params: dict[str, Any] | None = None,+) -> dict:+ if params:+ url = f"{url}?{urlencode(params)}"+ response = session.request(method, url, json=json_body, timeout=60)++ # The API enforces 300 requests/minute per IP; 429 and transient 5xx are worth backing off on.+ if response.status_code == 429 or response.status_code >= 500:+ raise ConfluentCloudRetryableError(+ f"Confluent Cloud API error (retryable): status={response.status_code}, url={url}"+ )++ if not response.ok:+ logger.error(f"Confluent Cloud API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _next_page_token(data: dict) -> str | None:+ return ((data.get("meta") or {}).get("pagination") or {}).get("next_page_token")+++def _iter_descriptor_pages(+ session: requests.Session,+ descriptor_path: str,+ logger: FilteringBoundLogger,+ resource_type: str | None = None,+) -> Iterator[list[dict]]:+ url = f"{CONFLUENT_CLOUD_BASE_URL}/v2/metrics/{DATASET}/{descriptor_path}"+ params: dict[str, Any] = {"page_size": DESCRIPTOR_PAGE_SIZE}+ if resource_type:+ params["resource_type"] = resource_type++ page_token: str | None = None+ while True:+ page_params = {**params, "page_token": page_token} if page_token else params+ data = _fetch_json(session, "GET", url, logger, params=page_params)+ items = data.get("data", [])+ if items:+ yield items+ page_token = _next_page_token(data)+ if not page_token:+ break+++def _get_metric_names(session: requests.Session, resource_type: str, logger: FilteringBoundLogger) -> list[str]:+ """List the queryable metric names for a resource type from the live descriptor catalog.++ Discovering the catalog at sync time means new Confluent metrics start flowing without a code+ change. Deprecated metrics are excluded — they stop returning data and eventually get removed.+ """+ names: list[str] = []+ for page in _iter_descriptor_pages(session, "descriptors/metrics", logger, resource_type=resource_type):+ for descriptor in page:+ if descriptor.get("lifecycle_stage") == "DEPRECATED":+ continue+ name = descriptor.get("name")+ if name:+ names.append(name)+ return names+++def _build_query_body(metric: str, resource_label: str, resource_ids: list[str], interval: str) -> dict[str, Any]:+ id_filters: list[dict[str, Any]] = [+ {"field": resource_label, "op": "EQ", "value": resource_id} for resource_id in resource_ids+ ]+ query_filter = id_filters[0] if len(id_filters) == 1 else {"op": "OR", "filters": id_filters}+ return {+ # The query endpoint accepts exactly one aggregation per request, so each metric is its+ # own query.+ "aggregations": [{"metric": metric}],+ "filter": query_filter,+ "granularity": GRANULARITY,+ "group_by": [resource_label],+ "intervals": [interval],+ "limit": QUERY_GROUP_LIMIT,+ "format": "FLAT",+ }+++def _iter_query_pages(+ session: requests.Session, body: dict[str, Any], logger: FilteringBoundLogger+) -> Iterator[list[dict]]:+ """POST a metrics query and follow `next_page_token` pages.++ Per the API spec, pagination re-POSTs the identical body with the token passed as the+ `page_token` query parameter. Tokens are short-lived, but each page is requested immediately+ after the previous one, and our absolute-timestamp intervals keep them valid across pages.+ """+ url = f"{CONFLUENT_CLOUD_BASE_URL}/v2/metrics/{DATASET}/query"+ page_token: str | None = None+ while True:+ params = {"page_token": page_token} if page_token else None+ data = _fetch_json(session, "POST", url, logger, json_body=body, params=params)+ items = data.get("data", [])+ if items:+ yield items+ page_token = _next_page_token(data)+ if not page_token:+ break+++def _normalize_point(point: dict[str, Any], metric: str, resource_label: str) -> dict[str, Any]:+ """Reshape a FLAT-format point into a stable row: the grouped resource id label (e.g.+ `resource.kafka.id`) becomes a plain `resource_id` column and the queried metric name is+ attached, forming the [metric, resource_id, timestamp] primary key."""+ return {+ "metric": metric,+ "resource_id": point.get(resource_label),+ "timestamp": point.get("timestamp"),+ "value": point.get("value"),+ }+++def _sync_range(+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ now: datetime,+) -> tuple[datetime, datetime]:+ retention_floor = now - timedelta(days=DEFAULT_LOOKBACK_DAYS)+ start = retention_floor+ if should_use_incremental_field:+ watermark = _coerce_datetime(db_incremental_field_last_value)+ if watermark is not None:+ # Cap a future-dated watermark at now, then re-pull a trailing overlap because recent+ # buckets get restated; merge dedupes on the primary key. Never reach past retention.+ start = max(min(watermark, now) - INCREMENTAL_OVERLAP, retention_floor)+ return start, now+++def _iter_metrics_rows(+ session: requests.Session,+ endpoint: str,+ resource_ids: list[str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ConfluentCloudResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict]]:+ config = CONFLUENT_CLOUD_ENDPOINTS[endpoint]+ assert config.resource_type is not None and config.resource_label is not None++ if not resource_ids:+ raise MissingResourceIdsError(+ f"No Confluent Cloud resource IDs configured for table '{endpoint}'. "+ "Add the resource IDs in the source settings, or disable this table."+ )++ start, end = _sync_range(should_use_incremental_field, db_incremental_field_last_value, datetime.now(UTC))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.window_start:+ resumed_start = _coerce_datetime(resume.window_start)+ if resumed_start is not None and start <= resumed_start < end:+ start = resumed_start+ logger.debug(f"Confluent Cloud: resuming {endpoint} from window start {resume.window_start}")++ metric_names = _get_metric_names(session, config.resource_type, logger)+ if not metric_names:+ logger.warning(f"Confluent Cloud: no metrics found for resource type {config.resource_type}")+ return++ window_start = start+ while window_start < end:+ window_end = min(window_start + QUERY_WINDOW, end)+ interval = f"{_format_timestamp(window_start)}/{_format_timestamp(window_end)}"++ for metric in metric_names:+ body = _build_query_body(metric, config.resource_label, resource_ids, interval)+ for page in _iter_query_pages(session, body, logger):+ yield [_normalize_point(point, metric, config.resource_label) for point in page]++ window_start = window_end+ # Checkpoint AFTER the window's rows are yielded (and only while more windows remain), so a+ # crash re-yields the current window rather than skipping it — merge dedupes on the primary+ # key.+ if window_start < end:+ resumable_source_manager.save_state(+ ConfluentCloudResumeConfig(window_start=_format_timestamp(window_start))+ )+++def get_rows(+ api_key: str,+ api_secret: str,+ endpoint: str,+ resource_ids: list[str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ConfluentCloudResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict]]:+ config = CONFLUENT_CLOUD_ENDPOINTS[endpoint]+ session = _make_session(api_key, api_secret)++ if config.kind == "descriptors":+ assert config.descriptor_path is not None+ yield from _iter_descriptor_pages(session, config.descriptor_path, logger)+ return++ yield from _iter_metrics_rows(+ session,+ endpoint,+ resource_ids,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+++def confluent_cloud_source(+ api_key: str,+ api_secret: str,+ endpoint: str,+ resource_ids: list[str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ConfluentCloudResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = CONFLUENT_CLOUD_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ api_secret=api_secret,+ endpoint=endpoint,+ resource_ids=resource_ids,+ 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,+ # The API returns points newest-first within each group, and we interleave per-metric+ # queries per window — rows are not globally ascending, so the incremental watermark must+ # only persist at successful job end (desc mode).+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def validate_credentials(+ api_key: str,+ api_secret: str,+ probe_metric: str,+ resource_label: str,+ resource_id: str,+ logger: FilteringBoundLogger | None = None,+) -> tuple[bool, int | None]:+ """Probe the query endpoint (the descriptor endpoints are public, so only a query proves the+ key). Returns ``(ok, status_code)``; ``status_code`` is ``None`` on a transport error."""+ session = _make_session(api_key, api_secret)+ now = datetime.now(UTC)+ body = _build_query_body(+ probe_metric,+ resource_label,+ [resource_id],+ f"{_format_timestamp(now - timedelta(hours=1))}/{_format_timestamp(now)}",+ )+ url = f"{CONFLUENT_CLOUD_BASE_URL}/v2/metrics/{DATASET}/query"+ try:+ response = session.post(url, json=body, timeout=15)+ except Exception:+ return False, None+ return response.status_code == 200, response.status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/settings.pynew file mode 100644index 000000000000..1e26ad9d5ecb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/settings.py@@ -0,0 +1,132 @@+from dataclasses import dataclass, field+from datetime import timedelta+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++CONFLUENT_CLOUD_BASE_URL = "https://api.telemetry.confluent.cloud"+DATASET = "cloud"++# Granularity of the time-series buckets we request. PT1H keeps rows compact and, per the API's+# validation table, allows intervals of any length (finer granularities cap the interval).+GRANULARITY = "PT1H"++# Metrics are walked in day-sized windows: small enough that a retried window is cheap to re-pull,+# large enough that a full 7-day backfill is only ~7 queries per metric.+QUERY_WINDOW = timedelta(days=1)++# The Metrics API retains data for about 7 days, so a first sync can never reach further back.+DEFAULT_LOOKBACK_DAYS = 7++# Incremental syncs re-pull a trailing overlap because recent buckets can be restated (metric data+# lands with up to ~5 minutes delay and the in-progress hour is partial). Merge dedupes on the+# primary key.+INCREMENTAL_OVERLAP = timedelta(hours=2)++DESCRIPTOR_PAGE_SIZE = 1000+# `limit` caps the number of result *groups* (i.e. resources, since we group by the resource id+# label); 1000 is the API maximum.+QUERY_GROUP_LIMIT = 1000++_TIMESTAMP_INCREMENTAL_FIELD: list[IncrementalField] = [+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class ConfluentCloudEndpointConfig:+ name: str+ kind: Literal["descriptors", "metrics"]+ primary_keys: list[str]+ # Descriptor endpoints: path under /v2/metrics/{dataset}/.+ descriptor_path: Optional[str] = None+ # Metrics endpoints: the descriptor `resources` type, its id label, the source-config field+ # holding the user's resource ids, and a known-stable metric used to probe credentials.+ resource_type: Optional[str] = None+ resource_label: Optional[str] = None+ config_ids_field: Optional[str] = None+ probe_metric: Optional[str] = None+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++CONFLUENT_CLOUD_ENDPOINTS: dict[str, ConfluentCloudEndpointConfig] = {+ "metric_descriptors": ConfluentCloudEndpointConfig(+ name="metric_descriptors",+ kind="descriptors",+ descriptor_path="descriptors/metrics",+ primary_keys=["name"],+ ),+ "resource_descriptors": ConfluentCloudEndpointConfig(+ name="resource_descriptors",+ kind="descriptors",+ descriptor_path="descriptors/resources",+ primary_keys=["type"],+ ),+ "kafka_metrics": ConfluentCloudEndpointConfig(+ name="kafka_metrics",+ kind="metrics",+ resource_type="kafka",+ resource_label="resource.kafka.id",+ config_ids_field="kafka_cluster_ids",+ probe_metric="io.confluent.kafka.server/received_bytes",+ primary_keys=["metric", "resource_id", "timestamp"],+ partition_key="timestamp",+ incremental_fields=_TIMESTAMP_INCREMENTAL_FIELD,+ ),+ "connector_metrics": ConfluentCloudEndpointConfig(+ name="connector_metrics",+ kind="metrics",+ resource_type="connector",+ resource_label="resource.connector.id",+ config_ids_field="connector_ids",+ probe_metric="io.confluent.kafka.connect/sent_bytes",+ primary_keys=["metric", "resource_id", "timestamp"],+ partition_key="timestamp",+ incremental_fields=_TIMESTAMP_INCREMENTAL_FIELD,+ ),+ "ksqldb_metrics": ConfluentCloudEndpointConfig(+ name="ksqldb_metrics",+ kind="metrics",+ resource_type="ksql",+ resource_label="resource.ksql.id",+ config_ids_field="ksqldb_cluster_ids",+ probe_metric="io.confluent.kafka.ksql/committed_offset_lag",+ primary_keys=["metric", "resource_id", "timestamp"],+ partition_key="timestamp",+ incremental_fields=_TIMESTAMP_INCREMENTAL_FIELD,+ ),+ "schema_registry_metrics": ConfluentCloudEndpointConfig(+ name="schema_registry_metrics",+ kind="metrics",+ resource_type="schema_registry",+ resource_label="resource.schema_registry.id",+ config_ids_field="schema_registry_ids",+ probe_metric="io.confluent.kafka.schema_registry/schema_count",+ primary_keys=["metric", "resource_id", "timestamp"],+ partition_key="timestamp",+ incremental_fields=_TIMESTAMP_INCREMENTAL_FIELD,+ ),+ "compute_pool_metrics": ConfluentCloudEndpointConfig(+ name="compute_pool_metrics",+ kind="metrics",+ resource_type="compute_pool",+ resource_label="resource.compute_pool.id",+ config_ids_field="compute_pool_ids",+ probe_metric="io.confluent.flink/compute_pool_utilization/cfu_limit",+ primary_keys=["metric", "resource_id", "timestamp"],+ partition_key="timestamp",+ incremental_fields=_TIMESTAMP_INCREMENTAL_FIELD,+ ),+}++ENDPOINTS = tuple(CONFLUENT_CLOUD_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CONFLUENT_CLOUD_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/source.pyindex 7e502deb5aeb..624ed5f499d9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/source.py@@ -1,21 +1,52 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.confluent_cloud.confluent_cloud import (+ ConfluentCloudResumeConfig,+ confluent_cloud_source,+ parse_resource_ids,+ validate_credentials as validate_confluent_cloud_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.confluent_cloud.settings import (+ CONFLUENT_CLOUD_ENDPOINTS,+ DEFAULT_LOOKBACK_DAYS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ ConfluentCloudEndpointConfig,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (ConfluentCloudSourceConfig,)from products.warehouse_sources.backend.types import ExternalDataSourceType+# Used to probe the query endpoint when the user configured no resource ids at all: a genuine key+# gets 403 (not authorized for this unknown cluster), a bad key gets 401.+_FALLBACK_PROBE_RESOURCE_ID = "lkc-00000"+@SourceRegistry.register-class ConfluentCloudSource(SimpleSource[ConfluentCloudSourceConfig]):+class ConfluentCloudSource(ResumableSource[ConfluentCloudSourceConfig, ConfluentCloudResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CONFLUENTCLOUD@@ -25,8 +56,224 @@ class ConfluentCloudSource(SimpleSource[ConfluentCloudSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.CONFLUENT_CLOUD,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="Confluent, Inc. (Confluent Cloud)",+ label="Confluent Cloud",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["kafka", "flink", "ksqldb", "metrics"],+ caption="""Warehouse your Confluent Cloud operational metrics (throughput, consumer lag, connector and Flink utilization) beyond the Metrics API's ~7 day retention window.++Create a **Cloud API key** (resource management scope, not a cluster-scoped key) owned by a service account with the **MetricsViewer** role, under **Administration → API keys** in the [Confluent Cloud console](https://confluent.cloud/settings/api-keys).++Then list the IDs of the resources to collect metrics for — for example Kafka cluster IDs (`lkc-...`) from **Cluster settings**. Leave a resource type blank to skip it.""",iconPath="/static/services/confluent_cloud.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/confluent-cloud",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Cloud API key",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_secret",+ label="Cloud API secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="kafka_cluster_ids",+ label="Kafka cluster IDs",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="lkc-abc123, lkc-def456",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="connector_ids",+ label="Connector IDs",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="lcc-abc123",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="ksqldb_cluster_ids",+ label="ksqlDB cluster IDs",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="lksqlc-abc123",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="schema_registry_ids",+ label="Schema Registry cluster IDs",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="lsrc-abc123",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="compute_pool_ids",+ label="Flink compute pool IDs",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="lfcp-abc123",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.confluent_cloud.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch_json` calls `raise_for_status()`.+ # Retrying can never fix a credential/permission problem, so fail the sync. Match the+ # stable status text and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.telemetry.confluent.cloud": "Your Confluent Cloud API key or secret is invalid or has been revoked. Create a new Cloud API key and reconnect.",+ "403 Client Error: Forbidden for url: https://api.telemetry.confluent.cloud": "Your Confluent Cloud API key is not authorized for the configured resources. Make sure it is a Cloud API key (not cluster-scoped) owned by a service account with the MetricsViewer role.",+ "No Confluent Cloud resource IDs configured": None,+ }++ def _resource_ids_for_endpoint(+ self, config: ConfluentCloudSourceConfig, endpoint_config: ConfluentCloudEndpointConfig+ ) -> list[str]:+ if not endpoint_config.config_ids_field:+ return []+ return parse_resource_ids(getattr(config, endpoint_config.config_ids_field, None))++ def get_schemas(+ self,+ config: ConfluentCloudSourceConfig,+ 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 = CONFLUENT_CLOUD_ENDPOINTS[endpoint]+ is_metrics = endpoint_config.kind == "metrics"+ description: str | None = None+ if is_metrics:+ description = (+ f"Hourly time-series values for every {endpoint_config.resource_type} metric in the "+ f"Metrics API catalog, aggregated per resource. The API retains about "+ f"{DEFAULT_LOOKBACK_DAYS} days of data, so the first sync backfills that window and "+ "regular syncs keep history beyond it."+ )+ return SourceSchema(+ name=endpoint,+ supports_incremental=is_metrics,+ # Incremental syncs re-pull a trailing overlap window that only merge dedupes on the+ # primary key; append would materialize those re-pulled rows as duplicates.+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ # Metrics tables need the matching resource ids to be queryable, so only tables the+ # user configured ids for start enabled.+ should_sync_default=bool(self._resource_ids_for_endpoint(config, endpoint_config))+ if is_metrics+ else True,+ description=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 get_endpoint_permissions(+ self, config: ConfluentCloudSourceConfig, team_id: int, endpoints: list[str]+ ) -> dict[str, str | None]:+ permissions: dict[str, str | None] = {}+ for endpoint in endpoints:+ endpoint_config = CONFLUENT_CLOUD_ENDPOINTS.get(endpoint)+ if (+ endpoint_config is not None+ and endpoint_config.kind == "metrics"+ and not self._resource_ids_for_endpoint(config, endpoint_config)+ ):+ permissions[endpoint] = (+ f"No {endpoint_config.resource_type} resource IDs configured — add them in the source settings"+ )+ else:+ permissions[endpoint] = None+ return permissions++ def _credentials_probe(+ self, config: ConfluentCloudSourceConfig, schema_name: Optional[str]+ ) -> tuple[str, str, str, bool]:+ """Pick (probe_metric, resource_label, resource_id, is_real_resource) for the credential+ check. Prefers the requested schema's resources, then any configured resource, then a fake+ Kafka cluster id (403 on it still proves the key authenticates)."""+ candidates = [CONFLUENT_CLOUD_ENDPOINTS[schema_name]] if schema_name in CONFLUENT_CLOUD_ENDPOINTS else []+ candidates += [c for c in CONFLUENT_CLOUD_ENDPOINTS.values() if c.kind == "metrics"]+ for endpoint_config in candidates:+ if endpoint_config.kind != "metrics":+ continue+ resource_ids = self._resource_ids_for_endpoint(config, endpoint_config)+ if resource_ids:+ assert endpoint_config.probe_metric is not None and endpoint_config.resource_label is not None+ return endpoint_config.probe_metric, endpoint_config.resource_label, resource_ids[0], True++ kafka = CONFLUENT_CLOUD_ENDPOINTS["kafka_metrics"]+ assert kafka.probe_metric is not None and kafka.resource_label is not None+ return kafka.probe_metric, kafka.resource_label, _FALLBACK_PROBE_RESOURCE_ID, False++ def validate_credentials(+ self, config: ConfluentCloudSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ probe_metric, resource_label, resource_id, is_real_resource = self._credentials_probe(config, schema_name)+ ok, status_code = validate_confluent_cloud_credentials(+ config.api_key, config.api_secret, probe_metric, resource_label, resource_id+ )++ if ok:+ return True, None+ if status_code == 401:+ return False, "Invalid Confluent Cloud API key or secret"+ if status_code == 403:+ if is_real_resource:+ return (+ False,+ f"Your API key authenticated but is not authorized to read metrics for '{resource_id}'. "+ "Use a Cloud API key owned by a service account with the MetricsViewer role.",+ )+ # The key authenticated (a bad key would get 401); it just isn't authorized for the+ # placeholder resource we probed with, which is expected.+ return True, None+ return False, "Could not connect to Confluent Cloud with the provided API key and secret"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ConfluentCloudResumeConfig]:+ return ResumableSourceManager[ConfluentCloudResumeConfig](inputs, ConfluentCloudResumeConfig)++ def source_for_pipeline(+ self,+ config: ConfluentCloudSourceConfig,+ resumable_source_manager: ResumableSourceManager[ConfluentCloudResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ endpoint_config = CONFLUENT_CLOUD_ENDPOINTS[inputs.schema_name]+ return confluent_cloud_source(+ api_key=config.api_key,+ api_secret=config.api_secret,+ endpoint=inputs.schema_name,+ resource_ids=self._resource_ids_for_endpoint(config, endpoint_config),+ 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/confluent_cloud/tests/test_confluent_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/tests/test_confluent_cloud.pynew file mode 100644index 000000000000..a7a7aa9cf968--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/tests/test_confluent_cloud.py@@ -0,0 +1,339 @@+from datetime import UTC, datetime+from typing import Any++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.confluent_cloud import confluent_cloud+from products.warehouse_sources.backend.temporal.data_imports.sources.confluent_cloud.confluent_cloud import (+ ConfluentCloudResumeConfig,+ MissingResourceIdsError,+ _build_query_body,+ _normalize_point,+ _sync_range,+ get_rows,+ parse_resource_ids,+)++_NOW = datetime(2026, 7, 15, 12, 0, 0, tzinfo=UTC)+++class TestParseResourceIds:+ @parameterized.expand(+ [+ ("comma_separated", "lkc-1, lkc-2", ["lkc-1", "lkc-2"]),+ ("whitespace_separated", "lkc-1 lkc-2", ["lkc-1", "lkc-2"]),+ ("mixed_and_padded", " lkc-1 ,, lkc-2 lkc-3 ", ["lkc-1", "lkc-2", "lkc-3"]),+ ("dedupes_preserving_order", "lkc-2, lkc-1, lkc-2", ["lkc-2", "lkc-1"]),+ ("empty_string", "", []),+ ("none", None, []),+ ]+ )+ def test_parse(self, _name: str, raw: str | None, expected: list[str]) -> None:+ assert parse_resource_ids(raw) == expected+++class TestSyncRange:+ @parameterized.expand(+ [+ # No watermark: backfill the full ~7-day retention window.+ ("first_sync", False, None, datetime(2026, 7, 8, 12, 0, tzinfo=UTC)),+ (+ "full_refresh_ignores_watermark",+ False,+ datetime(2026, 7, 14, tzinfo=UTC),+ datetime(2026, 7, 8, 12, 0, tzinfo=UTC),+ ),+ # Watermark minus the 2h restatement overlap.+ ("incremental", True, datetime(2026, 7, 14, 12, 0, tzinfo=UTC), datetime(2026, 7, 14, 10, 0, tzinfo=UTC)),+ # A future-dated watermark is clamped to now before the overlap is applied.+ (+ "future_watermark_clamped",+ True,+ datetime(2027, 1, 1, tzinfo=UTC),+ datetime(2026, 7, 15, 10, 0, tzinfo=UTC),+ ),+ # A stale watermark can't reach past the API's retention floor.+ (+ "stale_watermark_floored",+ True,+ datetime(2026, 6, 1, tzinfo=UTC),+ datetime(2026, 7, 8, 12, 0, tzinfo=UTC),+ ),+ # String watermarks (as persisted) parse too.+ ("string_watermark", True, "2026-07-14T12:00:00Z", datetime(2026, 7, 14, 10, 0, tzinfo=UTC)),+ ]+ )+ def test_range(self, _name: str, incremental: bool, watermark: Any, expected_start: datetime) -> None:+ start, end = _sync_range(incremental, watermark, _NOW)+ assert start == expected_start+ assert end == _NOW+++class TestBuildQueryBody:+ def test_single_id_uses_field_filter(self) -> None:+ body = _build_query_body(+ "io.confluent.kafka.server/received_bytes",+ "resource.kafka.id",+ ["lkc-1"],+ "2026-07-14T00:00:00Z/2026-07-15T00:00:00Z",+ )+ assert body == {+ "aggregations": [{"metric": "io.confluent.kafka.server/received_bytes"}],+ "filter": {"field": "resource.kafka.id", "op": "EQ", "value": "lkc-1"},+ "granularity": "PT1H",+ "group_by": ["resource.kafka.id"],+ "intervals": ["2026-07-14T00:00:00Z/2026-07-15T00:00:00Z"],+ "limit": 1000,+ "format": "FLAT",+ }++ def test_multiple_ids_use_or_filter(self) -> None:+ body = _build_query_body(+ "io.confluent.kafka.server/received_bytes",+ "resource.kafka.id",+ ["lkc-1", "lkc-2"],+ "2026-07-14T00:00:00Z/2026-07-15T00:00:00Z",+ )+ assert body["filter"] == {+ "op": "OR",+ "filters": [+ {"field": "resource.kafka.id", "op": "EQ", "value": "lkc-1"},+ {"field": "resource.kafka.id", "op": "EQ", "value": "lkc-2"},+ ],+ }+++class TestNormalizePoint:+ def test_resource_label_becomes_resource_id(self) -> None:+ point = {"timestamp": "2026-07-14T00:00:00Z", "value": 42.5, "resource.kafka.id": "lkc-1"}+ assert _normalize_point(point, "io.confluent.kafka.server/received_bytes", "resource.kafka.id") == {+ "metric": "io.confluent.kafka.server/received_bytes",+ "resource_id": "lkc-1",+ "timestamp": "2026-07-14T00:00:00Z",+ "value": 42.5,+ }+++class _FakeResumableManager:+ def __init__(self, state: ConfluentCloudResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[ConfluentCloudResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> ConfluentCloudResumeConfig | None:+ return self._state++ def save_state(self, data: ConfluentCloudResumeConfig) -> None:+ self.saved.append(data)+++class _FakeApi:+ """Routes `_fetch_json` calls: serves a metric-descriptor catalog and records queries."""++ def __init__(+ self,+ metric_descriptors: list[dict] | None = None,+ query_pages: list[dict] | None = None,+ descriptor_pages: list[dict] | None = None,+ ) -> None:+ self.metric_descriptors = metric_descriptors or []+ # Consumed one per query request; the last one repeats if queries outnumber pages.+ self.query_pages = query_pages or [{"data": []}]+ self.descriptor_pages = descriptor_pages or []+ self.queries: list[dict] = [] # {"body": ..., "params": ...} per POST++ def __call__(+ self,+ session: Any,+ method: str,+ url: str,+ logger: Any,+ json_body: dict | None = None,+ params: dict | None = None,+ ) -> dict:+ if method == "POST":+ self.queries.append({"body": json_body, "params": params})+ index = min(len(self.queries) - 1, len(self.query_pages) - 1)+ return self.query_pages[index]+ if "descriptors/metrics" in url and params and "resource_type" in params:+ return {"data": self.metric_descriptors, "meta": {"pagination": {}}}+ # Plain descriptor listing (metric_descriptors / resource_descriptors tables).+ token = (params or {}).get("page_token")+ page_index = 0 if token is None else int(token)+ page = self.descriptor_pages[page_index]+ return page+++def _collect(monkeypatch: Any, api: _FakeApi, manager: _FakeResumableManager, **kwargs: Any) -> list[dict]:+ monkeypatch.setattr(confluent_cloud, "_fetch_json", api)+ rows: list[dict] = []+ for batch in get_rows(+ api_key="key",+ api_secret="secret",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows+++_GA_METRIC = {"name": "io.confluent.kafka.server/received_bytes", "lifecycle_stage": "GENERAL_AVAILABILITY"}+_DEPRECATED_METRIC = {"name": "io.confluent.kafka.server/old_metric", "lifecycle_stage": "DEPRECATED"}+++class TestDescriptorRows:+ def test_paginates_descriptor_pages_with_page_token(self, monkeypatch: Any) -> None:+ api = _FakeApi(+ descriptor_pages=[+ {"data": [{"name": "m1"}], "meta": {"pagination": {"next_page_token": "1"}}},+ {"data": [{"name": "m2"}], "meta": {"pagination": {}}},+ ]+ )+ rows = _collect(monkeypatch, api, _FakeResumableManager(), endpoint="metric_descriptors", resource_ids=[])++ assert [r["name"] for r in rows] == ["m1", "m2"]+++class TestMetricsRows:+ def test_raises_when_no_resource_ids_configured(self, monkeypatch: Any) -> None:+ api = _FakeApi()+ with pytest.raises(MissingResourceIdsError):+ _collect(monkeypatch, api, _FakeResumableManager(), endpoint="kafka_metrics", resource_ids=[])++ @freeze_time(_NOW)+ def test_windows_metrics_and_rows(self, monkeypatch: Any) -> None:+ api = _FakeApi(+ metric_descriptors=[_GA_METRIC, _DEPRECATED_METRIC],+ query_pages=[{"data": [{"timestamp": "2026-07-14T10:00:00Z", "value": 1.0, "resource.kafka.id": "lkc-1"}]}],+ )+ rows = _collect(+ monkeypatch,+ api,+ _FakeResumableManager(),+ endpoint="kafka_metrics",+ resource_ids=["lkc-1"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 7, 14, 12, 0, tzinfo=UTC),+ )++ # Watermark 14T12:00 minus 2h overlap = 14T10:00, walked in day windows to now (15T12:00):+ # [14T10:00 → 15T10:00] then [15T10:00 → 15T12:00], one query per window for the one+ # non-deprecated metric.+ intervals = [q["body"]["intervals"] for q in api.queries]+ assert intervals == [+ ["2026-07-14T10:00:00Z/2026-07-15T10:00:00Z"],+ ["2026-07-15T10:00:00Z/2026-07-15T12:00:00Z"],+ ]+ for query in api.queries:+ assert query["body"]["aggregations"] == [{"metric": "io.confluent.kafka.server/received_bytes"}]++ assert rows[0] == {+ "metric": "io.confluent.kafka.server/received_bytes",+ "resource_id": "lkc-1",+ "timestamp": "2026-07-14T10:00:00Z",+ "value": 1.0,+ }++ @freeze_time(_NOW)+ def test_saves_state_after_each_completed_window_except_last(self, monkeypatch: Any) -> None:+ api = _FakeApi(metric_descriptors=[_GA_METRIC])+ manager = _FakeResumableManager()+ _collect(+ monkeypatch,+ api,+ manager,+ endpoint="kafka_metrics",+ resource_ids=["lkc-1"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 7, 14, 12, 0, tzinfo=UTC),+ )++ assert manager.saved == [ConfluentCloudResumeConfig(window_start="2026-07-15T10:00:00Z")]++ @freeze_time(_NOW)+ def test_resumes_from_saved_window(self, monkeypatch: Any) -> None:+ api = _FakeApi(metric_descriptors=[_GA_METRIC])+ manager = _FakeResumableManager(ConfluentCloudResumeConfig(window_start="2026-07-15T10:00:00Z"))+ _collect(+ monkeypatch,+ api,+ manager,+ endpoint="kafka_metrics",+ resource_ids=["lkc-1"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 7, 14, 12, 0, tzinfo=UTC),+ )++ intervals = [q["body"]["intervals"] for q in api.queries]+ assert intervals == [["2026-07-15T10:00:00Z/2026-07-15T12:00:00Z"]]++ @freeze_time(_NOW)+ def test_query_pagination_reposts_identical_body_with_page_token(self, monkeypatch: Any) -> None:+ api = _FakeApi(+ metric_descriptors=[_GA_METRIC],+ query_pages=[+ {+ "data": [{"timestamp": "2026-07-15T10:00:00Z", "value": 1.0, "resource.kafka.id": "lkc-1"}],+ "meta": {"pagination": {"next_page_token": "tok-1"}},+ },+ {"data": [{"timestamp": "2026-07-15T11:00:00Z", "value": 2.0, "resource.kafka.id": "lkc-2"}]},+ ],+ )+ rows = _collect(+ monkeypatch,+ api,+ _FakeResumableManager(),+ endpoint="kafka_metrics",+ resource_ids=["lkc-1", "lkc-2"],+ should_use_incremental_field=True,+ # One 2h window (after the overlap), so both queries belong to the same request body.+ db_incremental_field_last_value=datetime(2026, 7, 15, 12, 0, tzinfo=UTC),+ )++ assert len(api.queries) == 2+ assert api.queries[0]["params"] is None+ assert api.queries[1]["params"] == {"page_token": "tok-1"}+ assert api.queries[0]["body"] == api.queries[1]["body"]+ assert [r["value"] for r in rows] == [1.0, 2.0]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", 200, (True, 200)),+ ("bad_key", 401, (False, 401)),+ ("unauthorized_resource", 403, (False, 403)),+ ]+ )+ def test_status_mapping(self, _name: str, status_code: int, expected: tuple[bool, int | None]) -> None:+ session = MagicMock()+ session.post.return_value.status_code = status_code+ with (+ freeze_time(_NOW),+ pytest.MonkeyPatch.context() as mp,+ ):+ mp.setattr(confluent_cloud, "_make_session", lambda *a, **k: session)+ result = confluent_cloud.validate_credentials(+ "key", "secret", "io.confluent.kafka.server/received_bytes", "resource.kafka.id", "lkc-1"+ )+ assert result == expected++ body = session.post.call_args.kwargs["json"]+ assert body["intervals"] == ["2026-07-15T11:00:00Z/2026-07-15T12:00:00Z"]+ assert body["filter"] == {"field": "resource.kafka.id", "op": "EQ", "value": "lkc-1"}++ def test_transport_error_returns_none_status(self) -> None:+ session = MagicMock()+ session.post.side_effect = ConnectionError("boom")+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(confluent_cloud, "_make_session", lambda *a, **k: session)+ assert confluent_cloud.validate_credentials(+ "key", "secret", "io.confluent.kafka.server/received_bytes", "resource.kafka.id", "lkc-1"+ ) == (False, None)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/tests/test_confluent_cloud_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/tests/test_confluent_cloud_source.pynew file mode 100644index 000000000000..b7d27ff40b3c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/tests/test_confluent_cloud_source.py@@ -0,0 +1,225 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.confluent_cloud.confluent_cloud import (+ ConfluentCloudResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.confluent_cloud.settings import (+ CONFLUENT_CLOUD_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.confluent_cloud.source import ConfluentCloudSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (+ ConfluentCloudSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++_METRICS_ENDPOINTS = {name for name, c in CONFLUENT_CLOUD_ENDPOINTS.items() if c.kind == "metrics"}+_DESCRIPTOR_ENDPOINTS = set(ENDPOINTS) - _METRICS_ENDPOINTS++_VALIDATE_PATH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.confluent_cloud.source."+ "validate_confluent_cloud_credentials"+)+++class TestConfluentCloudSource:+ def setup_method(self):+ self.source = ConfluentCloudSource()+ self.team_id = 123+ self.config = ConfluentCloudSourceConfig(+ api_key="cloud-key", api_secret="cloud-secret", kafka_cluster_ids="lkc-111, lkc-222"+ )++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CONFLUENTCLOUD++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "ConfluentCloud"+ assert config.label == "Confluent Cloud"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/confluent_cloud.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/confluent-cloud"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == [+ "api_key",+ "api_secret",+ "kafka_cluster_ids",+ "connector_ids",+ "ksqldb_cluster_ids",+ "schema_registry_ids",+ "compute_pool_ids",+ ]++ def test_api_secret_field_is_secret_password(self):+ config = self.source.get_source_config+ secret_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_secret"+ )+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_field.secret is True+ assert secret_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.telemetry.confluent.cloud/v2/metrics/cloud/query",+ "403 Client Error: Forbidden for url: https://api.telemetry.confluent.cloud/v2/metrics/cloud/query",+ "No Confluent Cloud resource IDs configured for table 'kafka_metrics'. Add the resource IDs in the source settings, or disable this table.",+ ],+ )+ def test_non_retryable_errors_match_permanent_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://api.telemetry.confluent.cloud/v2/metrics/cloud/query",+ "500 Server Error: Internal Server Error for url: https://api.telemetry.confluent.cloud/v2/metrics/cloud/query",+ "HTTPSConnectionPool(host='api.telemetry.confluent.cloud', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_sync_modes(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name in _METRICS_ENDPOINTS:+ assert schemas[name].supports_incremental is True+ # The incremental overlap re-pull needs merge dedupe; append would duplicate rows.+ assert schemas[name].supports_append is False+ assert [f["field"] for f in schemas[name].incremental_fields] == ["timestamp"]+ for name in _DESCRIPTOR_ENDPOINTS:+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_default_sync_follows_configured_ids(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["kafka_metrics"].should_sync_default is True+ assert schemas["connector_metrics"].should_sync_default is False+ assert schemas["metric_descriptors"].should_sync_default is True++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["kafka_metrics"])+ assert [s.name for s in schemas] == ["kafka_metrics"]++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials_publishes_catalog(self):+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(CONFLUENT_CLOUD_ENDPOINTS)++ def test_endpoint_permissions_flag_unconfigured_metrics_tables(self):+ permissions = self.source.get_endpoint_permissions(self.config, self.team_id, list(ENDPOINTS))++ assert permissions["kafka_metrics"] is None+ assert permissions["metric_descriptors"] is None+ assert "No connector resource IDs configured" in (permissions["connector_metrics"] or "")++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message_fragment",+ [+ ((True, 200), True, None),+ ((False, 401), False, "Invalid Confluent Cloud API key or secret"),+ ((False, 403), False, "not authorized to read metrics for 'lkc-111'"),+ ((False, None), False, "Could not connect to Confluent Cloud"),+ ],+ )+ @mock.patch(_VALIDATE_PATH)+ def test_validate_credentials_with_configured_resource(+ self, mock_validate, mock_return, expected_valid, expected_message_fragment+ ):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ if expected_message_fragment is None:+ assert error_message is None+ else:+ assert expected_message_fragment in (error_message or "")+ # Probes with the first configured Kafka cluster id.+ assert mock_validate.call_args.args[3:] == ("resource.kafka.id", "lkc-111")++ @mock.patch(_VALIDATE_PATH)+ def test_validate_credentials_403_on_placeholder_resource_is_valid(self, mock_validate):+ # With no resource ids configured we probe a fake cluster: 403 proves the key+ # authenticated (a bad key would 401), so the credentials are accepted.+ mock_validate.return_value = (False, 403)+ config = ConfluentCloudSourceConfig(api_key="cloud-key", api_secret="cloud-secret")++ is_valid, error_message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is True+ assert error_message is None++ @mock.patch(_VALIDATE_PATH)+ def test_validate_credentials_probes_requested_schema_resource_first(self, mock_validate):+ mock_validate.return_value = (True, 200)+ config = ConfluentCloudSourceConfig(+ api_key="cloud-key",+ api_secret="cloud-secret",+ kafka_cluster_ids="lkc-111",+ connector_ids="lcc-999",+ )++ self.source.validate_credentials(config, self.team_id, schema_name="connector_metrics")++ assert mock_validate.call_args.args[3:] == ("resource.connector.id", "lcc-999")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is ConfluentCloudResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.confluent_cloud.source.confluent_cloud_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "kafka_metrics"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-07-14T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "cloud-key"+ assert kwargs["api_secret"] == "cloud-secret"+ assert kwargs["endpoint"] == "kafka_metrics"+ assert kwargs["resource_ids"] == ["lkc-111", "lkc-222"]+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == "2026-07-14T00:00:00Z"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.confluent_cloud.source.confluent_cloud_source"+ )+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "metric_descriptors"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-07-14T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["db_incremental_field_last_value"] is None+ assert kwargs["resource_ids"] == []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 659375438622..308f8283d19d 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@@ -1044,7 +1044,13 @@ class ConfluenceSourceConfig(config.Config):@config.configclass ConfluentCloudSourceConfig(config.Config):- pass+ api_key: str+ api_secret: str+ kafka_cluster_ids: str | None = None+ connector_ids: str | None = None+ ksqldb_cluster_ids: str | None = None+ schema_registry_ids: str | None = None+ compute_pool_ids: str | None = None@config.config