: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 honeycomb import source (#71156)
Tom Owers7818ea98654e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 8b23c3506154..d04b56705745 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -227,6 +227,7 @@ the row lists both.| heroku | HTTP | requests | ✅ || hetzner | HTTP | requests | ✅ || hibob | HTTP | requests | ✅ |+| honeycomb | HTTP | requests | ✅ || humanitix | HTTP | requests | ✅ || hubplanner | HTTP | requests | ✅ || hubspot | HTTP | requests | ✅ |@@ -689,7 +690,6 @@ doesn't conflict with concurrent PRs.- high_level- hightouch- honeybadger-- honeycomb- hoorayhr- hubplanner- humanitixdiff --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 abb9605e8ee4..37ad0e67d821 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@@ -1968,7 +1968,8 @@ class HoneybadgerSourceConfig(config.Config):@config.configclass HoneycombSourceConfig(config.Config):- pass+ api_key: str+ region: Literal["us", "eu"] = config.value(default="us")@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/canonical_descriptions.pynew file mode 100644index 000000000000..9a1d954858e8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/canonical_descriptions.py@@ -0,0 +1,128 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "datasets": {+ "description": "A dataset in the environment: a named collection of events sharing a schema, the unit most Honeycomb resources are scoped to.",+ "docs_url": "https://api-docs.honeycomb.io/api/datasets",+ "columns": {+ "name": "Human-readable name of the dataset.",+ "slug": "URL-safe unique identifier of the dataset within its environment.",+ "description": "Optional description of the dataset.",+ "expand_json_depth": "Maximum depth to which ingested JSON is automatically unpacked into columns.",+ "created_at": "When the dataset was created.",+ "last_written_at": "When an event was last written to the dataset.",+ },+ },+ "columns": {+ "description": "A queryable column in a dataset's schema, created automatically as events with new fields arrive.",+ "docs_url": "https://api-docs.honeycomb.io/api/columns",+ "columns": {+ "id": "Unique identifier for the column.",+ "dataset_slug": "Slug of the dataset the column belongs to (added by PostHog during sync).",+ "key_name": "Name of the column as it appears in events and queries.",+ "type": "Data type of the column (string, integer, float, or boolean).",+ "description": "Optional description of the column.",+ "hidden": "Whether the column is hidden from autocomplete and the schema view.",+ "last_written": "When an event containing this column was last received.",+ "created_at": "When the column was created.",+ "updated_at": "When the column was last modified.",+ },+ },+ "derived_columns": {+ "description": "A derived column: a virtual column computed from other columns with an expression, usable in queries, triggers, and SLOs. Environment-wide derived columns appear under the __all__ dataset slug.",+ "docs_url": "https://api-docs.honeycomb.io/api/derived-columns",+ "columns": {+ "id": "Unique identifier for the derived column.",+ "dataset_slug": "Slug of the dataset the derived column belongs to, or __all__ for environment-wide derived columns (added by PostHog during sync).",+ "alias": "Name of the derived column as used in queries.",+ "expression": "Formula that computes the derived column's value.",+ "description": "Optional description of the derived column.",+ "created_at": "When the derived column was created.",+ "updated_at": "When the derived column was last modified.",+ },+ },+ "slos": {+ "description": "A service level objective: a target percentage of qualified events matching a service level indicator over a rolling time period. Multi-dataset SLOs are listed once per dataset they span.",+ "docs_url": "https://api-docs.honeycomb.io/api/slos",+ "columns": {+ "id": "Unique identifier for the SLO.",+ "dataset_slug": "Slug of the dataset the SLO was listed under (added by PostHog during sync).",+ "name": "Human-readable name of the SLO.",+ "description": "Optional description of the SLO.",+ "sli": "The service level indicator: a derived column alias that classifies each event as passing or failing.",+ "time_period_days": "Rolling time window, in days, over which the SLO is evaluated.",+ "target_per_million": "Target number of qualified events per million that must pass the SLI.",+ "reset_at": "When the SLO's error budget was last manually reset, if ever.",+ "created_at": "When the SLO was created.",+ "updated_at": "When the SLO was last modified.",+ },+ },+ "burn_alerts": {+ "description": "A burn alert on an SLO, firing when the error budget is exhausted or projected to exhaust within a set window.",+ "docs_url": "https://api-docs.honeycomb.io/api/burn-alerts",+ "columns": {+ "id": "Unique identifier for the burn alert.",+ "dataset_slug": "Slug of the dataset whose SLO list surfaced this burn alert (added by PostHog during sync).",+ "slo_id": "Identifier of the SLO the burn alert monitors (added by PostHog during sync).",+ "alert_type": "Whether the alert fires on projected exhaustion time or on budget-rate drop.",+ "exhaustion_minutes": "For exhaustion-time alerts, minutes until budget exhaustion at which the alert fires.",+ "created_at": "When the burn alert was created.",+ "updated_at": "When the burn alert was last modified.",+ },+ },+ "triggers": {+ "description": "A trigger: a scheduled query with a threshold that notifies recipients when crossed.",+ "docs_url": "https://api-docs.honeycomb.io/api/triggers",+ "columns": {+ "id": "Unique identifier for the trigger.",+ "dataset_slug": "Slug of the dataset the trigger runs against (added by PostHog during sync).",+ "name": "Human-readable name of the trigger.",+ "description": "Optional description of the trigger.",+ "threshold": "Comparison operator and value the query result is evaluated against.",+ "frequency": "How often the trigger's query runs, in seconds.",+ "disabled": "Whether the trigger is currently disabled.",+ "triggered": "Whether the trigger is currently in a triggered state.",+ "created_at": "When the trigger was created.",+ "updated_at": "When the trigger was last modified.",+ },+ },+ "markers": {+ "description": "A marker: a point or span annotation (commonly a deploy) overlaid on query graphs. Environment-wide markers appear under the __all__ dataset slug.",+ "docs_url": "https://api-docs.honeycomb.io/api/markers",+ "columns": {+ "id": "Unique identifier for the marker.",+ "dataset_slug": "Slug of the dataset the marker belongs to, or __all__ for environment-wide markers (added by PostHog during sync).",+ "message": "Label shown for the marker.",+ "type": "Grouping type of the marker (e.g. deploy), which also determines its color.",+ "start_time": "Start of the marker as a Unix timestamp in seconds.",+ "end_time": "End of the marker as a Unix timestamp in seconds; absent for point-in-time markers.",+ "url": "Optional link target for the marker.",+ "created_at": "When the marker was created.",+ "updated_at": "When the marker was last modified.",+ },+ },+ "boards": {+ "description": "A board: a saved collection of queries and visualizations for a team or service.",+ "docs_url": "https://api-docs.honeycomb.io/api/boards",+ "columns": {+ "id": "Unique identifier for the board.",+ "name": "Human-readable name of the board.",+ "description": "Optional description of the board.",+ "style": "Layout style of the board.",+ "queries": "The queries pinned to the board, with their dataset and display settings.",+ },+ },+ "recipients": {+ "description": "A notification recipient (email, Slack, PagerDuty, webhook, or MS Teams) that triggers and burn alerts can notify.",+ "docs_url": "https://api-docs.honeycomb.io/api/recipients",+ "columns": {+ "id": "Unique identifier for the recipient.",+ "type": "Delivery mechanism of the recipient (e.g. email, slack, pagerduty, webhook).",+ "details": "Type-specific delivery settings, such as the target address or channel. Credential-bearing fields (integration keys, webhook URLs and secrets) are redacted by PostHog during sync.",+ "created_at": "When the recipient was created.",+ "updated_at": "When the recipient was last modified.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/honeycomb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/honeycomb.pynew file mode 100644index 000000000000..d3bed5ebee89--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/honeycomb.py@@ -0,0 +1,287 @@+import dataclasses+from collections.abc import Iterator+from typing import Any++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.honeycomb.settings import (+ HONEYCOMB_ENDPOINTS,+ HoneycombEndpointConfig,+ HoneycombScope,+)++# Honeycomb hosts a separate API instance per region; keys are region-specific, so requests+# against the wrong host 401 even with a valid key.+HONEYCOMB_BASE_URLS: dict[str, str] = {+ "us": "https://api.honeycomb.io",+ "eu": "https://api.eu1.honeycomb.io",+}+# Honeycomb's keyword for environment-scoped resources (markers, derived columns) that live+# outside any real dataset.+ENVIRONMENT_WIDE_SLUG = "__all__"++# Recipient payloads carry live credentials: PagerDuty integration keys, webhook signing+# secrets, and webhook / MS Teams URLs (capability URLs). Those must never land in a+# warehouse table any project member can query, so recipient `details` are filtered to an+# allow-list — unknown keys (new recipient types) are redacted, failing closed.+SAFE_RECIPIENT_DETAIL_KEYS = frozenset({"email_address", "slack_channel", "webhook_name", "pagerduty_integration_name"})+# Recipient types whose `target` (the abbreviated form embedded in trigger / burn-alert rows)+# is a plain address rather than a credential.+SAFE_RECIPIENT_TARGET_TYPES = frozenset({"email", "slack"})+# Endpoints whose raw responses contain recipient credentials — excluded from HTTP sample+# capture so unsanitized bodies are never persisted (still metered and logged).+ENDPOINTS_WITH_CREDENTIAL_PAYLOADS = frozenset({"recipients", "triggers", "burn_alerts"})+REDACTED_VALUE = "[REDACTED]"+++class HoneycombRetryableError(Exception):+ pass+++class HoneycombResumeConfig:+ # The fan-out dataset currently being processed, bookmarked by its stable slug (not a+ # positional index) so datasets created/deleted between a crash and the retry can't resume+ # us into the wrong dataset. The bookmarked dataset is re-fetched in full on resume — its+ # rows may not have been durably flushed — and merge dedupes on the primary key. None for+ # environment-level endpoints, which are a single request with nothing to resume.+ dataset_slug: str | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "X-Honeycomb-Team": api_key,+ "Content-Type": "application/json",+ }+++def _base_url(region: str) -> str:+ return HONEYCOMB_BASE_URLS.get(region, HONEYCOMB_BASE_URLS["us"])+++@retry(+ retry=retry_if_exception_type((HoneycombRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger):+ response = session.get(url, headers=headers, timeout=60)++ # Honeycomb rate limits per key/team and returns 429 on exceed; retry those plus+ # transient 5xx with exponential backoff.+ if response.status_code == 429 or response.status_code >= 500:+ raise HoneycombRetryableError(f"Honeycomb API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # 404s are expected during the fan-out (a dataset deleted mid-sync, or a plan/permission+ # gap on the __all__ pseudo-dataset) and handled by the caller.+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"Honeycomb API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response+++def _fetch_list(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> list[dict[str, Any]]:+ """Fetch a Honeycomb v1 list endpoint, which returns the full collection as one JSON array.++ Honeycomb's v1 config endpoints (datasets, columns, triggers, SLOs, markers, boards,+ recipients) are unpaginated. A non-list body has no rows to emit, so it is logged and+ treated as empty rather than crashing the sync on an unexpected shape."""+ response = _fetch_page(session, url, headers, logger)+ data = response.json()+ if not isinstance(data, list):+ logger.warning(f"Honeycomb: expected a JSON array from {url}, got {type(data).__name__}; skipping")+ return []+ return data+++def _fetch_list_skipping_missing(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> list[dict[str, Any]]:+ """Fetch a fan-out list, treating 404 as empty.++ A dataset deleted between enumeration and this fetch 404s, as does the ``__all__``+ pseudo-dataset on endpoints/plans where it isn't available. Neither should fail the+ whole sync — the rows are genuinely absent. Any other HTTP error is re-raised."""+ try:+ return _fetch_list(session, url, headers, logger)+ except requests.HTTPError as exc:+ if exc.response is not None and exc.response.status_code == 404:+ return []+ raise+++def _sanitize_recipient(recipient: dict[str, Any]) -> dict[str, Any]:+ """Redact credential-bearing fields from a recipient object (full or embedded form)."""+ sanitized = dict(recipient)+ details = sanitized.get("details")+ if isinstance(details, dict):+ sanitized["details"] = {+ key: (value if key in SAFE_RECIPIENT_DETAIL_KEYS else REDACTED_VALUE) for key, value in details.items()+ }+ if "target" in sanitized and sanitized.get("type") not in SAFE_RECIPIENT_TARGET_TYPES:+ sanitized["target"] = REDACTED_VALUE+ return sanitized+++def _sanitize_row(endpoint_name: str, row: dict[str, Any]) -> dict[str, Any]:+ """Scrub recipient credentials from a row before it reaches the warehouse."""+ if endpoint_name == "recipients":+ return _sanitize_recipient(row)+ embedded = row.get("recipients")+ if isinstance(embedded, list):+ row = dict(row)+ row["recipients"] = [_sanitize_recipient(item) if isinstance(item, dict) else item for item in embedded]+ return row+++def _list_dataset_slugs(+ session: requests.Session, base_url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> list[str]:+ return [dataset["slug"] for dataset in _fetch_list(session, f"{base_url}/1/datasets", headers, logger)]+++def _rows_for_dataset(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ config: HoneycombEndpointConfig,+ dataset_slug: str,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ """Fetch one fan-out dataset's rows, injecting the dataset slug into each row."""+ url = f"{base_url}{config.path.format(dataset_slug=dataset_slug)}"++ if config.scope == HoneycombScope.PER_SLO:+ # Burn alerts are listed per SLO, so walk the dataset's SLOs first. A multi-dataset SLO+ # is listed under each dataset it spans; the (id, dataset_slug) primary key keeps the+ # re-fetched burn alerts distinct per dataset rather than multi-matching on merge.+ rows: list[dict[str, Any]] = []+ slos = _fetch_list_skipping_missing(session, f"{base_url}/1/slos/{dataset_slug}", headers, logger)+ for slo in slos:+ slo_id = slo["id"]+ items = _fetch_list_skipping_missing(session, f"{url}?slo_id={slo_id}", headers, logger)+ rows.extend(+ {**_sanitize_row(config.name, item), "dataset_slug": dataset_slug, "slo_id": slo_id} for item in items+ )+ return rows++ items = _fetch_list_skipping_missing(session, url, headers, logger)+ return [{**_sanitize_row(config.name, item), "dataset_slug": dataset_slug} for item in items]+++def _iter_fan_out(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ config: HoneycombEndpointConfig,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[HoneycombResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Walk every dataset and emit each dataset's rows as one batch, bookmarking progress.++ Full refresh: Honeycomb's config endpoints expose no server-side timestamp filter, so+ each sync re-walks every dataset. Rows re-pulled on resume dedupe on the composite+ primary key."""+ dataset_slugs = _list_dataset_slugs(session, base_url, headers, logger)+ if config.include_environment_wide:+ dataset_slugs.append(ENVIRONMENT_WIDE_SLUG)++ # Resolve the saved bookmark to the slice of datasets still to process. The bookmarked+ # dataset itself is re-fetched — its rows may have been yielded but not durably flushed+ # before the crash. If it no longer exists, start over; merge dedupes the re-pulled rows.+ resume = manager.load_state() if manager.can_resume() else None+ start_index = 0+ if resume is not None and resume.dataset_slug is not None and resume.dataset_slug in dataset_slugs:+ start_index = dataset_slugs.index(resume.dataset_slug)+ logger.debug(f"Honeycomb: resuming {config.name} fan-out from dataset={resume.dataset_slug}")++ for dataset_slug in dataset_slugs[start_index:]:+ rows = _rows_for_dataset(session, base_url, headers, config, dataset_slug, logger)+ if not rows:+ continue+ yield rows+ # Save AFTER yielding so a crash re-yields this dataset rather than skipping it.+ manager.save_state(HoneycombResumeConfig(dataset_slug=dataset_slug))+++def get_rows(+ api_key: str,+ region: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HoneycombResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = HONEYCOMB_ENDPOINTS[endpoint]+ base_url = _base_url(region)+ headers = _get_headers(api_key)+ # One session reused across every request so urllib3 keeps the connection alive instead of+ # re-handshaking per request. Redact the key: it rides in the X-Honeycomb-Team header, which+ # the tracked transport's built-in scrubber doesn't recognise, so a logged/sampled request+ # would otherwise leak it. Responses carrying recipient credentials are additionally kept+ # out of HTTP sample capture — the name-based scrubbers can't recognise those payloads.+ session = make_tracked_session(redact_values=(api_key,), capture=endpoint not in ENDPOINTS_WITH_CREDENTIAL_PAYLOADS)++ if config.scope == HoneycombScope.ENVIRONMENT:+ rows = _fetch_list(session, f"{base_url}{config.path}", headers, logger)+ if rows:+ yield [_sanitize_row(config.name, row) for row in rows]+ return++ yield from _iter_fan_out(session, base_url, headers, config, logger, resumable_source_manager)+++def honeycomb_source(+ api_key: str,+ region: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HoneycombResumeConfig],+) -> SourceResponse:+ endpoint_config = HONEYCOMB_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ region=region,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=endpoint_config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )+++def validate_credentials(api_key: str, region: str) -> tuple[bool, str | None]:+ """Confirm the API key is genuine with one cheap probe of the auth endpoint.++ GET /1/auth describes the key and its scopes, so it works for any configuration key+ regardless of which per-resource permissions were granted."""+ url = f"{_base_url(region)}/1/auth"+ try:+ # Redact the key here too — see get_rows() for why the X-Honeycomb-Team header needs it.+ session = make_tracked_session(redact_values=(api_key,))+ response = session.get(url, headers=_get_headers(api_key), timeout=10)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Invalid Honeycomb API key. Check the key and that the selected region matches your account."+ return False, f"Honeycomb API error: {response.status_code}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/settings.pynew file mode 100644index 000000000000..1c732d7ba314--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/settings.py@@ -0,0 +1,125 @@+from dataclasses import dataclass, field+from enum import Enum+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField+++class HoneycombScope(Enum):+ """Where an endpoint lives in Honeycomb's resource hierarchy.++ A configuration API key is scoped to one Honeycomb environment. Some resources are+ environment-wide collections returned in a single request (datasets, boards, recipients);+ most are addressed per dataset (columns, triggers, SLOs, markers, …), so fetching those+ tables means fanning out one request per dataset. Burn alerts go one level deeper: they+ are listed per SLO, so the fan-out walks datasets -> SLOs -> burn alerts.+ """++ # Environment-wide collection returned by a single static path (GET /1/datasets).+ ENVIRONMENT = "environment"+ # Fan out over every dataset in the environment (GET /1/<resource>/{dataset_slug}).+ PER_DATASET = "per_dataset"+ # Fan out over every SLO in every dataset (GET /1/burn_alerts/{dataset_slug}?slo_id=…).+ PER_SLO = "per_slo"+++@dataclass+class HoneycombEndpointConfig:+ name: str+ scope: HoneycombScope+ # Path template. PER_DATASET and PER_SLO paths contain ``{dataset_slug}``; ENVIRONMENT+ # paths are static.+ path: str+ # Primary key columns used for merge dedup. For fan-out children the dataset slug is+ # included (and injected into every row) so the key stays unique across the whole table —+ # Honeycomb documents ids per resource, not globally, and multi-dataset SLOs are listed+ # under each dataset they span.+ primary_keys: list[str]+ # Stable, creation-time datetime column to partition by. Never an `updated_at` style+ # field — those move and would rewrite partitions every sync. None disables partitioning.+ partition_key: Optional[str] = None+ # Also fetch the environment-wide pseudo-dataset ``__all__`` after the per-dataset fan-out.+ # Honeycomb keeps environment-scoped markers and derived columns under that keyword rather+ # than any real dataset, so skipping it would silently drop them.+ include_environment_wide: bool = False+ # The menu of incremental cursor candidates advertised to the user. Empty = full refresh+ # only — none of Honeycomb's v1 config endpoints expose a server-side timestamp filter.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Whether the table is selected for sync by default in the connection wizard.+ should_sync_default: bool = True+++HONEYCOMB_ENDPOINTS: dict[str, HoneycombEndpointConfig] = {+ "datasets": HoneycombEndpointConfig(+ name="datasets",+ scope=HoneycombScope.ENVIRONMENT,+ path="/1/datasets",+ # Datasets have no id field; the slug is the unique identifier within an environment.+ primary_keys=["slug"],+ partition_key="created_at",+ ),+ "columns": HoneycombEndpointConfig(+ name="columns",+ scope=HoneycombScope.PER_DATASET,+ path="/1/columns/{dataset_slug}",+ primary_keys=["id", "dataset_slug"],+ partition_key="created_at",+ ),+ "derived_columns": HoneycombEndpointConfig(+ name="derived_columns",+ scope=HoneycombScope.PER_DATASET,+ path="/1/derived_columns/{dataset_slug}",+ primary_keys=["id", "dataset_slug"],+ partition_key="created_at",+ include_environment_wide=True,+ ),+ "slos": HoneycombEndpointConfig(+ name="slos",+ scope=HoneycombScope.PER_DATASET,+ path="/1/slos/{dataset_slug}",+ primary_keys=["id", "dataset_slug"],+ partition_key="created_at",+ ),+ "burn_alerts": HoneycombEndpointConfig(+ name="burn_alerts",+ scope=HoneycombScope.PER_SLO,+ path="/1/burn_alerts/{dataset_slug}",+ primary_keys=["id", "dataset_slug"],+ partition_key="created_at",+ ),+ "triggers": HoneycombEndpointConfig(+ name="triggers",+ scope=HoneycombScope.PER_DATASET,+ path="/1/triggers/{dataset_slug}",+ primary_keys=["id", "dataset_slug"],+ partition_key="created_at",+ ),+ "markers": HoneycombEndpointConfig(+ name="markers",+ scope=HoneycombScope.PER_DATASET,+ path="/1/markers/{dataset_slug}",+ primary_keys=["id", "dataset_slug"],+ partition_key="created_at",+ include_environment_wide=True,+ ),+ "boards": HoneycombEndpointConfig(+ name="boards",+ scope=HoneycombScope.ENVIRONMENT,+ path="/1/boards",+ # Boards carry no creation timestamp, so the table is unpartitioned.+ primary_keys=["id"],+ ),+ "recipients": HoneycombEndpointConfig(+ name="recipients",+ scope=HoneycombScope.ENVIRONMENT,+ path="/1/recipients",+ primary_keys=["id"],+ partition_key="created_at",+ ),+}++ENDPOINTS = tuple(HONEYCOMB_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in HONEYCOMB_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/source.pyindex 7f1d2e2c626a..a6f3d12122ae 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/source.py@@ -1,19 +1,46 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HoneycombSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.honeycomb.honeycomb import (+ HoneycombResumeConfig,+ honeycomb_source,+ validate_credentials as validate_honeycomb_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.honeycomb.settings import (+ ENDPOINTS,+ HONEYCOMB_ENDPOINTS,+ INCREMENTAL_FIELDS,+ HoneycombScope,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class HoneycombSource(SimpleSource[HoneycombSourceConfig]):+class HoneycombSource(ResumableSource[HoneycombSourceConfig, HoneycombResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.HONEYCOMB@@ -24,7 +51,117 @@ class HoneycombSource(SimpleSource[HoneycombSourceConfig]):name=SchemaExternalDataSourceType.HONEYCOMB,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Honeycomb",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter a Honeycomb configuration API key to pull your Honeycomb observability configuration — datasets, SLOs, burn alerts, triggers, markers, boards, and more — into the PostHog Data warehouse.++You can create a configuration key under **Environment settings → API keys** in your [Honeycomb account](https://ui.honeycomb.io/). Grant read access for the resources you want to sync: Manage Queries and Columns, Manage SLOs, Manage Triggers, Manage Markers, Manage Boards, and Manage Recipients.++Keys are region-specific — pick the region that matches your Honeycomb account.""",iconPath="/static/services/honeycomb.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/honeycomb",+ keywords=["observability", "slo", "tracing"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Configuration API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Configuration key",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (api.honeycomb.io)", value="us"),+ SourceFieldSelectConfigOption(label="EU (api.eu1.honeycomb.io)", value="eu"),+ ],+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # No amount of retrying fixes a bad, revoked, or under-permissioned key, so stop the+ # sync. Match the stable status text and base host (one per region), not the+ # per-request path/query.+ return {+ "401 Client Error: Unauthorized for url: https://api.honeycomb.io": "Your Honeycomb API key is invalid, revoked, or for a different region. Create a configuration key in your Honeycomb environment settings, then reconnect.",+ "401 Client Error: Unauthorized for url: https://api.eu1.honeycomb.io": "Your Honeycomb API key is invalid, revoked, or for a different region. Create a configuration key in your Honeycomb environment settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.honeycomb.io": "Your Honeycomb API key is missing a permission needed to sync this data. Grant the matching access (e.g. Manage SLOs, Manage Triggers) on the key, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.eu1.honeycomb.io": "Your Honeycomb API key is missing a permission needed to sync this data. Grant the matching access (e.g. Manage SLOs, Manage Triggers) on the key, then reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.honeycomb.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: HoneycombSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ endpoint_config = HONEYCOMB_ENDPOINTS[endpoint]+ if endpoint == "recipients":+ return (+ "Credential-bearing recipient fields (integration keys, webhook URLs and secrets) "+ "are redacted during sync."+ )+ if endpoint_config.scope is HoneycombScope.PER_SLO:+ return "One row per burn alert per dataset, fetched by walking every dataset's SLOs."+ if endpoint_config.include_environment_wide:+ return "Includes environment-wide rows under the __all__ dataset slug alongside per-dataset rows."+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = HONEYCOMB_ENDPOINTS[endpoint]+ # Full refresh only: Honeycomb's v1 config endpoints expose no server-side+ # timestamp filter, so a client-side cursor would still walk every row each run.+ return SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ description=_description(endpoint),+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: HoneycombSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_honeycomb_credentials(config.api_key, config.region)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HoneycombResumeConfig]:+ return ResumableSourceManager[HoneycombResumeConfig](inputs, HoneycombResumeConfig)++ def source_for_pipeline(+ self,+ config: HoneycombSourceConfig,+ resumable_source_manager: ResumableSourceManager[HoneycombResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return honeycomb_source(+ api_key=config.api_key,+ region=config.region,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb.pynew file mode 100644index 000000000000..713cad9d34c6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb.py@@ -0,0 +1,413 @@+import json+from collections.abc import Mapping+from typing import Any++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized+from tenacity import stop_after_attempt, wait_none++from products.warehouse_sources.backend.temporal.data_imports.sources.honeycomb import honeycomb+from products.warehouse_sources.backend.temporal.data_imports.sources.honeycomb.honeycomb import (+ HoneycombResumeConfig,+ HoneycombRetryableError,+ _base_url,+ _get_headers,+ get_rows,+ validate_credentials,+)++US = "https://api.honeycomb.io"+++class _FakeResumableManager:+ def __init__(self, state: HoneycombResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[HoneycombResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> HoneycombResumeConfig | None:+ return self._state++ def save_state(self, data: HoneycombResumeConfig) -> None:+ self.saved.append(data)+++def _make_response(status_code: int, body: Any = None) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ if body is not None:+ response._content = json.dumps(body).encode()+ return response+++class _FakeSession:+ """Returns queued responses in order, recording the URLs requested."""++ def __init__(self, responses: list[requests.Response]) -> None:+ self._responses = list(responses)+ self.requested_urls: list[str] = []++ def get(self, url: str, headers: dict[str, str] | None = None, timeout: int | None = None) -> requests.Response:+ self.requested_urls.append(url)+ return self._responses.pop(0)+++def _not_found(url: str) -> requests.HTTPError:+ return requests.HTTPError(f"404 Client Error: Not Found for url: {url}", response=_make_response(404))+++def _collect(+ endpoint: str,+ lists: Mapping[str, list[dict[str, Any]] | Exception],+ manager: _FakeResumableManager,+ monkeypatch: Any,+ region: str = "us",+) -> list[dict]:+ monkeypatch.setattr(honeycomb, "make_tracked_session", lambda *args, **kwargs: MagicMock())++ def fake_fetch_list(session: Any, url: str, headers: Any, logger: Any) -> list[dict]:+ if url not in lists:+ raise AssertionError(f"unexpected URL requested: {url}")+ result = lists[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(honeycomb, "_fetch_list", fake_fetch_list)++ rows: list[dict] = []+ for batch in get_rows(+ api_key="key",+ region=region,+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows+++class TestHelpers:+ def test_get_headers_sets_team_header(self) -> None:+ assert _get_headers("hcaik_123")["X-Honeycomb-Team"] == "hcaik_123"++ @parameterized.expand([("us", US), ("eu", "https://api.eu1.honeycomb.io"), ("unknown", US)])+ def test_base_url_per_region(self, region: str, expected: str) -> None:+ assert _base_url(region) == expected+++class TestFetchPage:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status_code: int) -> None:+ session = _FakeSession([_make_response(status_code) for _ in range(5)])+ # tenacity exposes retry_with on the decorated callable to rebuild it with different+ # retry settings; here we drop the backoff so the test doesn't actually sleep.+ fast_fetch = honeycomb._fetch_page.retry_with(wait=wait_none(), stop=stop_after_attempt(3)) # type: ignore[attr-defined]+ with pytest.raises(HoneycombRetryableError):+ fast_fetch(session, f"{US}/1/datasets", {}, MagicMock())++ def test_client_error_raises_http_error_without_retry(self) -> None:+ session = _FakeSession([_make_response(401, body={"error": "unknown API key"})])+ with pytest.raises(requests.HTTPError):+ honeycomb._fetch_page(session, f"{US}/1/datasets", {}, MagicMock()) # type: ignore[arg-type]+ assert len(session.requested_urls) == 1++ def test_fetch_list_treats_non_array_body_as_empty(self) -> None:+ session = _FakeSession([_make_response(200, body={"unexpected": "shape"})])+ assert honeycomb._fetch_list(session, f"{US}/1/datasets", {}, MagicMock()) == [] # type: ignore[arg-type]+++class TestEnvironmentEndpoints:+ def test_single_fetch_yields_all_rows(self, monkeypatch: Any) -> None:+ lists = {f"{US}/1/boards": [{"id": "b1"}, {"id": "b2"}]}+ rows = _collect("boards", lists, _FakeResumableManager(), monkeypatch)+ assert rows == [{"id": "b1"}, {"id": "b2"}]++ def test_eu_region_routes_to_eu_host(self, monkeypatch: Any) -> None:+ lists = {"https://api.eu1.honeycomb.io/1/boards": [{"id": "b1"}]}+ rows = _collect("boards", lists, _FakeResumableManager(), monkeypatch, region="eu")+ assert rows == [{"id": "b1"}]+++class TestPerDatasetFanOut:+ def test_walks_datasets_and_injects_dataset_slug(self, monkeypatch: Any) -> None:+ lists = {+ f"{US}/1/datasets": [{"slug": "prod"}, {"slug": "staging"}],+ f"{US}/1/columns/prod": [{"id": "c1"}],+ f"{US}/1/columns/staging": [{"id": "c1"}, {"id": "c2"}],+ }+ rows = _collect("columns", lists, _FakeResumableManager(), monkeypatch)+ assert rows == [+ {"id": "c1", "dataset_slug": "prod"},+ {"id": "c1", "dataset_slug": "staging"},+ {"id": "c2", "dataset_slug": "staging"},+ ]++ @parameterized.expand([("markers",), ("derived_columns",)])+ def test_environment_wide_pseudo_dataset_included(self, endpoint: str) -> None:+ # Environment-scoped markers/derived columns only exist under __all__; skipping it would+ # silently drop e.g. every environment-wide deploy marker from the table.+ lists = {+ f"{US}/1/datasets": [{"slug": "prod"}],+ f"{US}/1/{endpoint}/prod": [{"id": "r1"}],+ f"{US}/1/{endpoint}/__all__": [{"id": "r2"}],+ }+ # parameterized.expand can't also receive the `monkeypatch` fixture, so manage our own.+ with pytest.MonkeyPatch.context() as mp:+ rows = _collect(endpoint, lists, _FakeResumableManager(), mp)+ assert rows == [+ {"id": "r1", "dataset_slug": "prod"},+ {"id": "r2", "dataset_slug": "__all__"},+ ]++ def test_deleted_dataset_404_is_skipped(self, monkeypatch: Any) -> None:+ # A dataset deleted between enumeration and its fetch must not fail the whole sync.+ lists: dict[str, Any] = {+ f"{US}/1/datasets": [{"slug": "gone"}, {"slug": "prod"}],+ f"{US}/1/columns/gone": _not_found(f"{US}/1/columns/gone"),+ f"{US}/1/columns/prod": [{"id": "c1"}],+ }+ rows = _collect("columns", lists, _FakeResumableManager(), monkeypatch)+ assert rows == [{"id": "c1", "dataset_slug": "prod"}]++ def test_state_saved_after_each_yielded_dataset(self, monkeypatch: Any) -> None:+ lists = {+ f"{US}/1/datasets": [{"slug": "prod"}, {"slug": "empty"}, {"slug": "staging"}],+ f"{US}/1/columns/prod": [{"id": "c1"}],+ f"{US}/1/columns/empty": [],+ f"{US}/1/columns/staging": [{"id": "c2"}],+ }+ manager = _FakeResumableManager()+ _collect("columns", lists, manager, monkeypatch)+ # Empty datasets yield nothing so no checkpoint is written for them — a checkpoint must+ # only ever point at a dataset whose rows were actually handed to the pipeline.+ assert [state.dataset_slug for state in manager.saved] == ["prod", "staging"]++ def test_resume_refetches_bookmarked_dataset_and_skips_earlier(self, monkeypatch: Any) -> None:+ # The bookmarked dataset's rows may not have been durably flushed before the crash, so it+ # is re-fetched in full (merge dedupes); datasets before it must not be re-fetched (their+ # URLs are absent from `lists`, so a fetch would raise).+ lists = {+ f"{US}/1/datasets": [{"slug": "prod"}, {"slug": "staging"}, {"slug": "dev"}],+ f"{US}/1/columns/staging": [{"id": "c2"}],+ f"{US}/1/columns/dev": [{"id": "c3"}],+ }+ manager = _FakeResumableManager(HoneycombResumeConfig(dataset_slug="staging"))+ rows = _collect("columns", lists, manager, monkeypatch)+ assert rows == [+ {"id": "c2", "dataset_slug": "staging"},+ {"id": "c3", "dataset_slug": "dev"},+ ]++ def test_resume_from_deleted_dataset_restarts_from_first(self, monkeypatch: Any) -> None:+ lists = {+ f"{US}/1/datasets": [{"slug": "prod"}],+ f"{US}/1/columns/prod": [{"id": "c1"}],+ }+ manager = _FakeResumableManager(HoneycombResumeConfig(dataset_slug="GONE"))+ rows = _collect("columns", lists, manager, monkeypatch)+ assert rows == [{"id": "c1", "dataset_slug": "prod"}]+++class TestBurnAlertFanOut:+ def test_walks_datasets_then_slos_and_injects_both_ids(self, monkeypatch: Any) -> None:+ lists = {+ f"{US}/1/datasets": [{"slug": "prod"}],+ f"{US}/1/slos/prod": [{"id": "slo1"}, {"id": "slo2"}],+ f"{US}/1/burn_alerts/prod?slo_id=slo1": [{"id": "ba1"}],+ f"{US}/1/burn_alerts/prod?slo_id=slo2": [{"id": "ba2"}],+ }+ rows = _collect("burn_alerts", lists, _FakeResumableManager(), monkeypatch)+ assert rows == [+ {"id": "ba1", "dataset_slug": "prod", "slo_id": "slo1"},+ {"id": "ba2", "dataset_slug": "prod", "slo_id": "slo2"},+ ]++ def test_dataset_without_slos_yields_nothing(self, monkeypatch: Any) -> None:+ lists: dict[str, Any] = {+ f"{US}/1/datasets": [{"slug": "prod"}, {"slug": "quiet"}],+ f"{US}/1/slos/prod": [{"id": "slo1"}],+ f"{US}/1/burn_alerts/prod?slo_id=slo1": [{"id": "ba1"}],+ f"{US}/1/slos/quiet": [],+ }+ rows = _collect("burn_alerts", lists, _FakeResumableManager(), monkeypatch)+ assert rows == [{"id": "ba1", "dataset_slug": "prod", "slo_id": "slo1"}]+++class TestRecipientCredentialScrubbing:+ """Recipient payloads carry live credentials (PagerDuty integration keys, webhook signing+ secrets, webhook / MS Teams capability URLs). Dropping the sanitization would hand those to+ anyone with warehouse query access, so lock in the redaction behavior."""++ def test_recipient_details_are_allow_listed(self, monkeypatch: Any) -> None:+ lists: dict[str, list[dict[str, Any]]] = {+ f"{US}/1/recipients": [+ {"id": "r1", "type": "email", "details": {"email_address": "[email protected]"}},+ {+ "id": "r2",+ "type": "webhook",+ "details": {"webhook_name": "hook", "webhook_url": "https://h.example", "webhook_secret": "shh"},+ },+ {+ "id": "r3",+ "type": "pagerduty",+ "details": {"pagerduty_integration_name": "svc", "pagerduty_integration_key": "pd-key"},+ },+ # Unknown detail keys (new recipient types) must fail closed.+ {"id": "r4", "type": "msteams", "details": {"msteams_url": "https://teams.example/abc"}},+ ]+ }+ rows = _collect("recipients", lists, _FakeResumableManager(), monkeypatch)+ assert rows == [+ {"id": "r1", "type": "email", "details": {"email_address": "[email protected]"}},+ {+ "id": "r2",+ "type": "webhook",+ "details": {"webhook_name": "hook", "webhook_url": "[REDACTED]", "webhook_secret": "[REDACTED]"},+ },+ {+ "id": "r3",+ "type": "pagerduty",+ "details": {"pagerduty_integration_name": "svc", "pagerduty_integration_key": "[REDACTED]"},+ },+ {"id": "r4", "type": "msteams", "details": {"msteams_url": "[REDACTED]"}},+ ]++ def test_embedded_trigger_recipients_redact_credential_targets(self, monkeypatch: Any) -> None:+ # Triggers (and burn alerts) embed abbreviated recipients whose `target` holds the same+ # credentials for non-address types; only email/slack targets are plain addresses.+ lists: dict[str, list[dict[str, Any]]] = {+ f"{US}/1/datasets": [{"slug": "prod"}],+ f"{US}/1/triggers/prod": [+ {+ "id": "t1",+ "name": "High latency",+ "recipients": [+ {"id": "r1", "type": "email", "target": "[email protected]"},+ {"id": "r2", "type": "pagerduty", "target": "pd-integration-key"},+ ],+ }+ ],+ }+ rows = _collect("triggers", lists, _FakeResumableManager(), monkeypatch)+ assert rows == [+ {+ "id": "t1",+ "name": "High latency",+ "recipients": [+ {"id": "r1", "type": "email", "target": "[email protected]"},+ {"id": "r2", "type": "pagerduty", "target": "[REDACTED]"},+ ],+ "dataset_slug": "prod",+ }+ ]++ @parameterized.expand(+ [+ ("recipients", False),+ ("triggers", False),+ ("burn_alerts", False),+ ("boards", True),+ ("columns", True),+ ]+ )+ def test_credential_payload_endpoints_excluded_from_sample_capture(self, endpoint: str, expected: bool) -> None:+ # Raw responses for these endpoints contain unsanitized credentials, so they must not be+ # persisted by HTTP sample capture (the name-based scrubbers can't recognise them).+ captured: dict[str, Any] = {}++ def fake_make_session(*args: Any, **kwargs: Any) -> Any:+ captured.update(kwargs)+ return MagicMock()++ # parameterized.expand can't also receive the `monkeypatch` fixture, so manage our own.+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(honeycomb, "make_tracked_session", fake_make_session)+ mp.setattr(honeycomb, "_fetch_list", lambda *args, **kwargs: [])+ list(+ get_rows(+ api_key="key",+ region="us",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert captured.get("capture") is expected+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ ("forbidden", 403, False),+ ("server_error", 500, False),+ ]+ )+ def test_status_mapping(self, _name: str, status_code: int, expected_ok: bool) -> None:+ session = _FakeSession([_make_response(status_code, body={})])+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(honeycomb, "make_tracked_session", lambda *args, **kwargs: session)+ ok, _error = validate_credentials("key", "us")+ assert ok is expected_ok++ def test_probes_the_selected_regions_auth_endpoint(self) -> None:+ # A key validated against the wrong region always 401s, so the probe must follow the+ # user's region selection rather than defaulting to US.+ session = _FakeSession([_make_response(200, body={})])+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(honeycomb, "make_tracked_session", lambda *args, **kwargs: session)+ validate_credentials("key", "eu")+ assert session.requested_urls == ["https://api.eu1.honeycomb.io/1/auth"]++ def test_request_exception_is_failure(self, monkeypatch: Any) -> None:+ class _BoomSession:+ def get(self, *args: Any, **kwargs: Any) -> requests.Response:+ raise requests.exceptions.ConnectionError("boom")++ monkeypatch.setattr(honeycomb, "make_tracked_session", lambda *args, **kwargs: _BoomSession())+ ok, error = validate_credentials("key", "us")+ assert ok is False+ assert error is not None+++class TestApiKeyRedaction:+ """The key rides in the X-Honeycomb-Team header, which the tracked transport's scrubber+ doesn't recognise, so every session must redact the key by value."""++ def test_validate_credentials_redacts_key(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_make_session(*args: Any, **kwargs: Any) -> Any:+ captured.update(kwargs)+ return _FakeSession([_make_response(200, body={})])++ monkeypatch.setattr(honeycomb, "make_tracked_session", fake_make_session)+ validate_credentials("super-secret-key", "us")+ assert captured.get("redact_values") == ("super-secret-key",)++ def test_get_rows_redacts_key(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_make_session(*args: Any, **kwargs: Any) -> Any:+ captured.update(kwargs)+ return MagicMock()++ monkeypatch.setattr(honeycomb, "make_tracked_session", fake_make_session)+ monkeypatch.setattr(honeycomb, "_fetch_list", lambda *args, **kwargs: [])+ list(+ get_rows(+ api_key="super-secret-key",+ region="us",+ endpoint="boards",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert captured.get("redact_values") == ("super-secret-key",)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb_source.pynew file mode 100644index 000000000000..046226ad3854--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb_source.py@@ -0,0 +1,186 @@+from typing import Any++from unittest import mock+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HoneycombSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.honeycomb.honeycomb import HoneycombResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.honeycomb.settings import (+ ENDPOINTS,+ HONEYCOMB_ENDPOINTS,+ HoneycombScope,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.honeycomb.source import HoneycombSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _source_inputs(schema_name: str = "datasets") -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-1",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestHoneycombSource:+ def setup_method(self) -> None:+ self.source = HoneycombSource()+ self.team_id = 1++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.HONEYCOMB++ def test_source_config_basics(self) -> None:+ config = self.source.get_source_config+ assert config.label == "Honeycomb"+ assert config.unreleasedSource is None+ field_names = [f.name for f in config.fields]+ assert field_names == ["api_key", "region"]+ api_key_field = config.fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.required is True+ assert api_key_field.secret is True+ region_field = config.fields[1]+ assert isinstance(region_field, SourceFieldSelectConfig)+ assert {option.value for option in region_field.options} == {"us", "eu"}++ def test_generated_config_parses_fields(self) -> None:+ # Guards the generated_configs.py wiring: the form fields must map to `api_key` and+ # `region`, with the region defaulting to US for configs saved before the field existed.+ config = HoneycombSourceConfig.from_dict({"api_key": "hcaik_123"})+ assert config.api_key == "hcaik_123"+ assert config.region == "us"+ assert HoneycombSourceConfig.from_dict({"api_key": "k", "region": "eu"}).region == "eu"++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_all_schemas_are_full_refresh(self) -> None:+ # Honeycomb's v1 config endpoints have no server-side timestamp filter, so advertising+ # incremental would silently re-walk history every run while claiming a delta sync.+ for schema in self.source.get_schemas(MagicMock(), team_id=self.team_id):+ assert schema.supports_incremental is False, schema.name+ assert schema.supports_append is False, schema.name++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id, names=["datasets", "slos"])+ assert {s.name for s in schemas} == {"datasets", "slos"}++ def test_publishes_table_catalog_for_public_docs(self) -> None:+ # `lists_tables_without_credentials` gates whether the static endpoint catalog reaches+ # the posthog.com "Supported tables" section. Dropping the flag (or making get_schemas+ # require credentials) would silently empty that section.+ tables = self.source.get_documented_tables()+ names = {t["name"] for t in tables}+ assert set(ENDPOINTS).issubset(names)+ datasets = next(t for t in tables if t["name"] == "datasets")+ assert "Full refresh" in datasets["sync_methods"]+ assert datasets["description"]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.honeycomb.source.validate_honeycomb_credentials"+ )+ def test_validate_credentials_passes_region(self, mock_validate: MagicMock) -> None:+ mock_validate.return_value = (True, None)+ ok, error = self.source.validate_credentials(HoneycombSourceConfig(api_key="k", region="eu"), self.team_id)+ assert ok is True+ assert error is None+ mock_validate.assert_called_once_with("k", "eu")++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.honeycomb.source.validate_honeycomb_credentials"+ )+ def test_validate_credentials_failure(self, mock_validate: MagicMock) -> None:+ mock_validate.return_value = (False, "Invalid Honeycomb API key")+ ok, error = self.source.validate_credentials(HoneycombSourceConfig(api_key="bad"), self.team_id)+ assert ok is False+ assert error == "Invalid Honeycomb API key"++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is HoneycombResumeConfig++ @parameterized.expand(+ [+ ("datasets", ["slug"]),+ ("columns", ["id", "dataset_slug"]),+ ("slos", ["id", "dataset_slug"]),+ ("burn_alerts", ["id", "dataset_slug"]),+ ("boards", ["id"]),+ ("recipients", ["id"]),+ ]+ )+ def test_source_for_pipeline_plumbs_endpoint(self, endpoint: str, expected_keys: list[str]) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs(endpoint))+ response = self.source.source_for_pipeline(+ HoneycombSourceConfig(api_key="k", region="us"), manager, _source_inputs(endpoint)+ )+ assert response.name == endpoint+ assert response.primary_keys == expected_keys++ def test_fan_out_children_carry_dataset_slug_in_primary_key(self) -> None:+ # Fan-out children aggregate rows from every dataset (and multi-dataset SLOs are listed+ # under each dataset they span), so the injected dataset slug must be part of the primary+ # key — otherwise per-dataset-unique ids collide table-wide and every merge multi-matches.+ for config in HONEYCOMB_ENDPOINTS.values():+ if config.scope in (HoneycombScope.PER_DATASET, HoneycombScope.PER_SLO):+ assert "dataset_slug" in config.primary_keys, config.name++ @parameterized.expand(+ [+ (+ "unauthorized_us",+ "401 Client Error: Unauthorized for url: https://api.honeycomb.io/1/columns/prod?x=1",+ ),+ (+ "unauthorized_eu",+ "401 Client Error: Unauthorized for url: https://api.eu1.honeycomb.io/1/datasets",+ ),+ (+ "forbidden_us",+ "403 Client Error: Forbidden for url: https://api.honeycomb.io/1/slos/prod",+ ),+ (+ "forbidden_eu",+ "403 Client Error: Forbidden for url: https://api.eu1.honeycomb.io/1/boards",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.honeycomb.io/1/datasets"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.honeycomb.io/1/boards"),+ ("read_timeout", "HTTPSConnectionPool(host='api.honeycomb.io', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)++ def test_canonical_description_keys_are_real_endpoints(self) -> None:+ # Canonical descriptions are keyed by schema name; a typo'd key would silently never apply.+ descriptions: dict[str, Any] = self.source.get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)+ for endpoint, entry in descriptions.items():+ assert entry["description"], endpoint