Skip to content

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

feat(data-warehouse): implement height import source (#68588)

Tom Owersf04550aacc19
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 6039e9a0b258..b771a190cd05 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -181,6 +181,7 @@ the row lists both.
| gridly | HTTP | requests | ✅ |
| guardian | HTTP | requests | ✅ |
| guru | HTTP | requests | ✅ |
+| height | HTTP | requests | ✅ |
| hellobaton | HTTP | requests | ✅ |
| hibob | HTTP | requests | ✅ |
| hubplanner | HTTP | requests | ✅ |
@@ -479,7 +480,6 @@ doesn't conflict with concurrent PRs.
- gusto
- harness
- heap
-- height
- helpscout
- hibob
- high_level
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index f9af8cf2f2a0..dcfa8cd4a219 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
@@ -1521,7 +1521,7 @@ class HeapSourceConfig(config.Config):
@config.config
class HeightSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/height/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/height/canonical_descriptions.py
new file mode 100644
index 000000000000..35042330ad75
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/height/canonical_descriptions.py
@@ -0,0 +1,50 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Height API docs (https://height.notion.site/API-documentation).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+_HEIGHT_DOCS_URL = "https://height.notion.site/API-documentation-643aea5bf01742de9232ed5b8b23a91b"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "users": {
+ "description": "A member of your Height workspace.",
+ "docs_url": _HEIGHT_DOCS_URL,
+ "columns": {
+ "id": "The unique ID of the user.",
+ "email": "The user's email address.",
+ "username": "The user's username.",
+ "firstname": "The user's first name.",
+ "lastname": "The user's last name.",
+ "state": "The account state of the user (for example, enabled or disabled).",
+ "access": "The user's access level in the workspace.",
+ "createdAt": "When the user was created.",
+ },
+ },
+ "lists": {
+ "description": "A list (or smart list) that groups tasks in Height, such as a project or view.",
+ "docs_url": _HEIGHT_DOCS_URL,
+ "columns": {
+ "id": "The unique ID of the list.",
+ "name": "The name of the list.",
+ "description": "The list's description.",
+ "type": "The type of list (for example, list or smartlist).",
+ "appType": "The Height app the list belongs to.",
+ "key": "The short key used in the list's URL.",
+ "url": "The web URL of the list.",
+ "createdAt": "When the list was created.",
+ },
+ },
+ "field_templates": {
+ "description": "A custom field definition (field template) applied to tasks in Height.",
+ "docs_url": _HEIGHT_DOCS_URL,
+ "columns": {
+ "id": "The unique ID of the field template.",
+ "name": "The name of the field template.",
+ "type": "The field's data type (for example, text, number, or options).",
+ "appType": "The Height app the field template belongs to.",
+ "labels": "The set of labels (options) available for a labels-type field.",
+ "createdAt": "When the field template was created.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/height/height.py b/products/warehouse_sources/backend/temporal/data_imports/sources/height/height.py
new file mode 100644
index 000000000000..af409753cbb5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/height/height.py
@@ -0,0 +1,115 @@
+from collections.abc import Iterator
+from typing import Any, Optional
+
+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.height.settings import HEIGHT_ENDPOINTS
+
+HEIGHT_BASE_URL = "https://api.height.app"
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap endpoint used to confirm an API key is genuine. The key is workspace-wide, so one probe
+# validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/users"
+
+
+class HeightRetryableError(Exception):
+ pass
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ # Height's scheme is the literal word `api-key` followed by the secret, not a Bearer token.
+ return {"Authorization": f"api-key {api_key}", "Accept": "application/json"}
+
+
+@retry(
+ retry=retry_if_exception_type((HeightRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_list(
+ session: requests.Session,
+ path: str,
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ response = session.get(
+ f"{HEIGHT_BASE_URL}{path}",
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise HeightRetryableError(f"Height API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"Height API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ data = response.json()
+ # Height list endpoints wrap records in a top-level `list` key.
+ if not isinstance(data, dict) or not isinstance(data.get("list"), list):
+ raise HeightRetryableError(f"Height returned an unexpected payload for {path}: {type(data).__name__}")
+ return data["list"]
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ config = HEIGHT_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+
+ # These endpoints are unpaginated single-shot lists, so one request returns the full collection.
+ rows = _fetch_list(session, config.path, logger)
+ if rows:
+ yield rows
+
+
+def height_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = HEIGHT_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(api_key=api_key, endpoint=endpoint, logger=logger),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the API key.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ try:
+ response = session.get(f"{HEIGHT_BASE_URL}{path}", timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Height: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Height returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ status, message = check_access(api_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Height API key"
+ return False, message or "Could not validate Height API key"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/height/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/height/settings.py
new file mode 100644
index 000000000000..cb71a0b9a2b2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/height/settings.py
@@ -0,0 +1,24 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class HeightEndpointConfig:
+ name: str
+ path: str
+ # Every Height object exposes a globally unique `id`, so it is a safe primary key.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Height Core API top-level list endpoints. Each returns `{"list": [...]}` with no documented
+# pagination, so a single request pulls the whole collection. All are full-refresh only: only the
+# task search endpoint exposes a `lastActivityAt` filter, and that requires search params, so there
+# is no incremental cursor to advance across these reference resources.
+HEIGHT_ENDPOINTS: dict[str, HeightEndpointConfig] = {
+ "users": HeightEndpointConfig(name="users", path="/users"),
+ "lists": HeightEndpointConfig(name="lists", path="/lists"),
+ "field_templates": HeightEndpointConfig(name="field_templates", path="/fieldTemplates"),
+}
+
+ENDPOINTS = tuple(HEIGHT_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/height/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/height/source.py
index 117f485dc8bb..352f9da06369 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/height/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/height/source.py
@@ -1,19 +1,37 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HeightSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.height.height import (
+ height_source,
+ validate_credentials as _height_validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.height.settings import ENDPOINTS, HEIGHT_ENDPOINTS
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class HeightSource(SimpleSource[HeightSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.HEIGHT
@@ -24,7 +42,77 @@ class HeightSource(SimpleSource[HeightSourceConfig]):
name=SchemaExternalDataSourceType.HEIGHT,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Height",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Height API key to pull your project management data into the PostHog Data warehouse.
+
+You can create an API key on the **Settings → API** page in [Height](https://height.app/). The key grants read access to your workspace's users, lists, and field templates.
+""",
iconPath="/static/services/height.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/height",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="secret_...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.height.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.height.app": "Your Height API key is invalid or has been revoked. Generate a new key on the Settings → API page, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.height.app": "Your Height API key does not have access to this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: HeightSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — Height's list endpoints expose no server-side
+ # timestamp filter without search params, so there is no incremental cursor to advance.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ 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: HeightSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key is workspace-wide, so a single probe validates access to every schema.
+ return _height_validate_credentials(config.api_key)
+
+ def source_for_pipeline(self, config: HeightSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ if inputs.schema_name not in HEIGHT_ENDPOINTS:
+ raise ValueError(f"Unknown Height schema '{inputs.schema_name}'")
+
+ return height_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/height/tests/test_height.py b/products/warehouse_sources/backend/temporal/data_imports/sources/height/tests/test_height.py
new file mode 100644
index 000000000000..a8b0b1d35394
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/height/tests/test_height.py
@@ -0,0 +1,198 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.height import height
+from products.warehouse_sources.backend.temporal.data_imports.sources.height.height import (
+ HeightRetryableError,
+ check_access,
+ get_rows,
+ height_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.height.settings import ENDPOINTS, HEIGHT_ENDPOINTS
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_list_unwrapped = height._fetch_list.__wrapped__ # type: ignore[attr-defined]
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(monkeypatch: Any, rows: list[dict], endpoint: str = "users") -> list[dict]:
+ def fake_fetch(session: Any, path: str, logger: Any) -> list[dict]:
+ return rows
+
+ monkeypatch.setattr(height, "_fetch_list", fake_fetch)
+ monkeypatch.setattr(height, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ collected: list[dict] = []
+ for batch in get_rows(api_key="secret_key", endpoint=endpoint, logger=MagicMock()):
+ collected.extend(batch)
+ return collected
+
+ def test_yields_single_batch(self, monkeypatch: Any) -> None:
+ rows = self._collect(monkeypatch, [{"id": "a"}, {"id": "b"}])
+ assert rows == [{"id": "a"}, {"id": "b"}]
+
+ def test_empty_list_yields_nothing(self, monkeypatch: Any) -> None:
+ assert self._collect(monkeypatch, []) == []
+
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_every_endpoint_fetches_its_path(self, endpoint: str) -> None:
+ captured: dict[str, str] = {}
+
+ def fake_fetch(session: Any, path: str, logger: Any) -> list[dict]:
+ captured["path"] = path
+ return []
+
+ # Patch on the module so get_rows uses the fake, bypassing the network.
+ with mock.patch.object(height, "_fetch_list", fake_fetch):
+ list(get_rows(api_key="secret_key", endpoint=endpoint, logger=MagicMock()))
+
+ assert captured["path"] == HEIGHT_ENDPOINTS[endpoint].path
+
+
+class TestFetchList:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {"list": []}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(HeightRetryableError):
+ _fetch_list_unwrapped(session, "/users", MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_list_unwrapped(session, "/users", MagicMock())
+
+ def test_success_returns_list_key(self) -> None:
+ session = self._session_returning(200, {"list": [{"id": "x"}]})
+ result = _fetch_list_unwrapped(session, "/users", MagicMock())
+ assert result == [{"id": "x"}]
+
+ @parameterized.expand([("bare_array", [{"id": 1}]), ("missing_list_key", {"data": []}), ("null_body", None)])
+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:
+ # `None` maps to a body without a `list` key via the fixture default.
+ session = self._session_returning(200, body if body is not None else {"data": []})
+ with pytest.raises(HeightRetryableError):
+ _fetch_list_unwrapped(session, "/users", MagicMock())
+
+ def test_request_targets_base_url_and_path(self) -> None:
+ session = self._session_returning(200, {"list": []})
+ _fetch_list_unwrapped(session, "/lists", MagicMock())
+ args, _ = session.get.call_args
+ assert args[0] == "https://api.height.app/lists"
+
+
+class TestCheckAccess:
+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ monkeypatch.setattr(height, "make_tracked_session", lambda **kwargs: session)
+ return session
+
+ @parameterized.expand(
+ [
+ (200, True, 200, None),
+ (401, False, 401, None),
+ (403, False, 403, None),
+ (500, False, 500, "Height returned HTTP 500"),
+ ]
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.height.height.make_tracked_session")
+ def test_status_mapping(
+ self,
+ status: int,
+ ok: bool,
+ expected_status: int,
+ expected_message: str | None,
+ mock_make_session: mock.MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ session = MagicMock()
+ session.get.return_value = response
+ mock_make_session.return_value = session
+ assert check_access("secret_key") == (expected_status, expected_message)
+
+ def test_authorization_header_uses_api_key_scheme(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+
+ def fake_make_session(headers: dict[str, str], redact_values: Any) -> MagicMock:
+ captured["headers"] = headers
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ monkeypatch.setattr(height, "make_tracked_session", fake_make_session)
+ check_access("secret_abc")
+ assert captured["headers"]["Authorization"] == "api-key secret_abc"
+
+ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:
+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))
+ status, message = check_access("secret_key")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ (200, True, None),
+ (401, False, "Invalid Height API key"),
+ (403, False, "Invalid Height API key"),
+ (500, False, "Height returned HTTP 500"),
+ ]
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.height.height.make_tracked_session")
+ def test_validate_credentials(
+ self,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_make_session: mock.MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ session = MagicMock()
+ session.get.return_value = response
+ mock_make_session.return_value = session
+ assert validate_credentials("secret_key") == (expected_valid, expected_message)
+
+
+class TestHeightSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = height_source(api_key="secret_key", endpoint=endpoint, logger=MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ # No stable creation timestamp is guaranteed across every object, so we don't partition.
+ assert response.partition_mode is None
+
+ def test_every_endpoint_uses_id_primary_key(self) -> None:
+ assert all(config.primary_keys == ["id"] for config in HEIGHT_ENDPOINTS.values())
+ assert set(HEIGHT_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/height/tests/test_height_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/height/tests/test_height_source.py
new file mode 100644
index 000000000000..5687430ae2cc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/height/tests/test_height_source.py
@@ -0,0 +1,117 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HeightSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.height.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.height.source import HeightSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestHeightSource:
+ def setup_method(self) -> None:
+ self.source = HeightSource()
+ self.team_id = 123
+ self.config = HeightSourceConfig(api_key="secret_key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.HEIGHT
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Height"
+ assert config.label == "Height"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source is visible — it must not carry the scaffolding flag.
+ assert not config.unreleasedSource
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/height"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret
+ # field an editor could retarget to reuse a preserved key against another account.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["lists"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "lists"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://api.height.app/users",),
+ ("403 Client Error: Forbidden for url: https://api.height.app/lists",),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, 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(
+ [
+ ("500 Server Error: Internal Server Error for url: https://api.height.app/users",),
+ ("429 Client Error: Too Many Requests for url: https://api.height.app/lists",),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.height.source._height_validate_credentials"
+ )
+ def test_validate_credentials_delegates_to_height(self, mock_validate: mock.MagicMock) -> None:
+ # The status/message mapping is owned by height.validate_credentials (covered in test_height.py);
+ # here we only assert the source extracts the api key and returns the delegate's result unchanged.
+ mock_validate.return_value = (False, "Invalid Height API key")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ mock_validate.assert_called_once_with("secret_key")
+ assert result == (False, "Invalid Height API key")
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.height.source.height_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "users"
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "secret_key"
+ assert kwargs["endpoint"] == "users"
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Height schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, inputs)