: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 hex import source (#72619)
Tom Owers4361eaa474a2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 614fea29e2e7..5e62cc5c8ad5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -265,6 +265,7 @@ the row lists both.| hellobaton | HTTP | requests | ✅ || heroku | HTTP | requests | ✅ || hetzner | HTTP | requests | ✅ |+| hex | HTTP | requests + `rest_source.RESTClient` | ✅ || hibob | HTTP | requests | ✅ || honeybadger | HTTP | requests | ✅ || honeycomb | HTTP | requests | ✅ |@@ -765,7 +766,6 @@ doesn't conflict with concurrent PRs.- heap- helpscout- hetzner-- hex- heygen- hibob- high_leveldiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hex.pyindex 47eba128118b..baa407900187 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hex.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hex.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass HexSourceConfig(config.Config):- pass+ api_key: str+ workspace_url: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hex/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/canonical_descriptions.pynew file mode 100644index 000000000000..ab9bbf15176a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/canonical_descriptions.py@@ -0,0 +1,78 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://learn.hex.tech/docs/api-integrations/api/reference"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "projects": {+ "description": "A Hex project (notebook or app) in the workspace, including ownership, status, categories, usage analytics, and schedule metadata.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique UUID for the Hex project.",+ "title": "Title of the project.",+ "description": "Description of the project, if set.",+ "type": "Type of the project (e.g. PROJECT or COMPONENT).",+ "creator": "User who created the project (object with the creator's email).",+ "owner": "User who owns the project (object with the owner's email).",+ "status": "Workspace-defined project status, if set (object with the status name).",+ "categories": "Workspace-defined categories assigned to the project.",+ "reviews": "Whether reviews are required for the project.",+ "analytics": "Usage analytics for the project: published app views over trailing windows, last viewed time, and when published results were last updated.",+ "lastEditedAt": "UTC timestamp of when the project was last edited.",+ "lastPublishedAt": "UTC timestamp of when the project was last published, if ever.",+ "createdAt": "UTC timestamp of when the project was created.",+ "archivedAt": "UTC timestamp of when the project was archived, if archived.",+ "trashedAt": "UTC timestamp of when the project was moved to trash, if trashed.",+ "schedules": "Configured run schedules for the project (cadence, timezone, and enablement).",+ },+ },+ "project_runs": {+ "description": "An execution of a published Hex project triggered via the API, a schedule, or an app refresh, with its status and timing.",+ "docs_url": _DOCS_URL,+ "columns": {+ "projectId": "UUID of the Hex project this run belongs to.",+ "projectVersion": "Version of the project that was run.",+ "runId": "Unique UUID for the run.",+ "runUrl": "URL to view the run in Hex.",+ "status": "Current status of the run (PENDING, RUNNING, ERRORED, COMPLETED, KILLED, or UNABLE_TO_ALLOCATE_KERNEL).",+ "runTrigger": "How the run was triggered: API, SCHEDULED, or APP_REFRESH.",+ "startTime": "UTC timestamp of when the run started.",+ "endTime": "UTC timestamp of when the run finished.",+ "elapsedTime": "Total elapsed time for the run in milliseconds.",+ "traceId": "Trace ID for correlating the run with Hex support.",+ "notifications": "Notification recipients configured for the run.",+ },+ },+ "users": {+ "description": "A member of the Hex workspace with their role and last login time.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique UUID for the user.",+ "name": "Display name of the user, if set.",+ "email": "Email address of the user.",+ "role": "Workspace role of the user (e.g. ADMIN, EDITOR, MEMBER, GUEST).",+ "lastLoginDate": "UTC timestamp of the user's most recent login, if any.",+ },+ },+ "groups": {+ "description": "A permission group in the Hex workspace, used to manage access to projects and collections.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique UUID for the group.",+ "name": "Name of the group.",+ "createdAt": "UTC timestamp of when the group was created.",+ },+ },+ "collections": {+ "description": "A collection in the Hex workspace, used to organize and share sets of projects.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique UUID for the collection.",+ "name": "Name of the collection.",+ "description": "Description of the collection.",+ "creator": "User who created the collection (object with the creator's id and email).",+ "sharing": "Sharing configuration for the collection (users, groups, and workspace access).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hex/hex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/hex.pynew file mode 100644index 000000000000..73ab4ebe8696--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/hex.py@@ -0,0 +1,245 @@+import re+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests++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.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+ rest_api_resources,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+ OffsetPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.hex.settings import (+ HEX_ENDPOINTS,+ HexEndpointConfig,+)++DEFAULT_WORKSPACE_HOST = "app.hex.tech"+HOST_NOT_ALLOWED_ERROR = "Hex workspace URL is not allowed"+++class HexHostNotAllowedError(Exception):+ pass+++class HexResumeConfig:+ # Opaque paginator resume state: `{"cursor": ...}` for cursor-paginated endpoints, or the+ # framework's fan-out checkpoint (`{"completed": [...], "current": ..., "child_state": ...}`)+ # for project_runs.+ paginator_state: dict[str, Any]+++def normalize_workspace_host(workspace_url: Optional[str]) -> str:+ """Turn whatever the user typed into a bare Hex host.++ Accepts values like ``acme.hex.tech``, ``https://acme.hex.tech/``, or+ ``acme.hex.tech/api/v1`` and returns ``acme.hex.tech``. Blank means the Hex+ multi-tenant cloud (``app.hex.tech``).+ """+ host = (workspace_url or "").strip()+ if not host:+ return DEFAULT_WORKSPACE_HOST+ host = re.sub(r"^https?://", "", host, flags=re.IGNORECASE)+ host = host.split("/")[0]+ return host.strip() or DEFAULT_WORKSPACE_HOST+++def _base_url(workspace_url: Optional[str]) -> str:+ return f"https://{normalize_workspace_host(workspace_url)}/api"+++class HexCursorPaginator(JSONResponseCursorPaginator):+ """Hex cursor pagination: the next-page token arrives in ``pagination.after`` and is sent+ back as the ``after`` query param. An empty page ends pagination even if a token is present,+ so an API quirk can't loop us forever."""++ def __init__(self) -> None:+ super().__init__(cursor_path="pagination.after", cursor_param="after")++ def update_state(self, response: requests.Response, data: Optional[list[Any]] = None) -> None:+ if not data:+ self._has_next_page = False+ return+ super().update_state(response, data)+++def validate_credentials(+ workspace_url: Optional[str], api_key: str, schema_name: Optional[str] = None, team_id: Optional[int] = None+) -> tuple[bool, str | None]:+ """Probe ListProjects with limit=1 to confirm the bearer token is genuine.++ At source-create (``schema_name is None``) a 403 is accepted: the token is valid but may lack+ a permission for this particular probe. A scoped probe (``schema_name`` set) treats 403 as a+ hard failure.+ """+ host = normalize_workspace_host(workspace_url)+ if not re.match(r"^[A-Za-z0-9.\-]+$", host):+ return False, "Invalid Hex workspace URL"++ # The workspace host is customer-controlled (single-tenant deployments), so block hosts that+ # resolve to private/internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.+ if team_id is not None:+ host_ok, host_err = _is_host_safe(host, team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ url = f"https://{host}/api/v1/projects"+ try:+ # Don't follow redirects: the validated host could 3xx to an internal address, defeating+ # the host check above (SSRF).+ response = make_tracked_session(redact_values=(api_key,)).get(+ url,+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ params={"limit": 1},+ timeout=10,+ allow_redirects=False,+ )+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.is_redirect or response.is_permanent_redirect:+ return False, HOST_NOT_ALLOWED_ERROR++ if response.status_code == 200:+ return True, None++ if response.status_code == 401:+ return False, "Invalid Hex API token"++ if response.status_code == 403:+ if schema_name is None:+ # Valid token, missing permission for this probe — let source creation through.+ return True, None+ return False, "Hex API token lacks the required permissions for this endpoint"++ try:+ body = response.json()+ return False, str(body.get("reason") or body.get("message") or response.text)+ except Exception:+ return False, response.text+++def _endpoint_resource(config: HexEndpointConfig) -> EndpointResource:+ params: dict[str, Any] = dict(config.params)+ if config.pagination == "cursor":+ # The offset paginator injects limit/offset itself; cursor endpoints carry limit here.+ params["limit"] = config.page_size+ paginator: Any = HexCursorPaginator()+ else:+ # Runs responses carry no total count — pagination stops on a short or empty page.+ paginator = OffsetPaginator(limit=config.page_size, total_path=None)++ if config.parent is not None:+ params[config.resolve_param or ""] = {+ "type": "resolve",+ "resource": config.parent,+ "field": config.resolve_field,+ }++ resource: EndpointResource = {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": {+ "path": config.path,+ "params": params,+ "data_selector": config.data_selector,+ "paginator": paginator,+ },+ "table_format": "delta",+ }+ return resource+++def hex_source(+ api_key: str,+ workspace_url: Optional[str],+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[HexResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = HEX_ENDPOINTS[endpoint]++ client: ClientConfig = {+ "base_url": _base_url(workspace_url),+ # The bearer token rides the framework auth config so it is redacted from logs and+ # raised error messages.+ "auth": {"type": "bearer", "token": api_key},+ "headers": {"Accept": "application/json"},+ # A validated host could 3xx to an internal address; refuse to follow redirects (SSRF).+ "allow_redirects": False,+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = resume.paginator_state++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when there's something to resume to; save AFTER a page is yielded so a+ # crash re-fetches that page (merge dedupes) rather than skipping data.+ if state:+ resumable_source_manager.save_state(HexResumeConfig(paginator_state=state))++ if config.parent is not None:+ rest_config: RESTAPIConfig = {+ "client": client,+ "resource_defaults": {},+ "resources": [_endpoint_resource(HEX_ENDPOINTS[config.parent]), _endpoint_resource(config)],+ }+ resources = rest_api_resources(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ resource = next(r for r in resources if getattr(r, "name", None) == endpoint)+ else:+ resource = rest_api_resource(+ {"client": client, "resource_defaults": {}, "resources": [_endpoint_resource(config)]},+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ def items() -> Iterator[list[Any]]:+ # Re-check at run time (not just at source-create) in case the workspace URL was edited+ # or now resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ host_ok, host_err = _is_host_safe(normalize_workspace_host(workspace_url), team_id)+ if not host_ok:+ raise HexHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)+ yield from resource++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=list(config.primary_keys),+ sort_mode=config.sort_mode,+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hex/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/settings.pynew file mode 100644index 000000000000..1069a6df9de0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/settings.py@@ -0,0 +1,94 @@+from dataclasses import dataclass, field+from typing import Any, Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField+++@dataclass(frozen=True)+class HexEndpointConfig:+ name: str+ path: str+ data_selector: str+ primary_keys: tuple[str, ...]+ # "cursor" endpoints page via the `after` token in `pagination.after`; "offset" endpoints+ # (GetProjectRuns) page via numeric `limit`/`offset` params.+ pagination: Literal["cursor", "offset"]+ page_size: int = 100+ # Static query params sent on every request (explicit stable sort where the API supports one,+ # so page boundaries don't shift mid-sync).+ params: dict[str, Any] = field(default_factory=dict)+ # Stable, immutable field to partition by (never a field that mutates on edits).+ partition_key: Optional[str] = None+ # Endpoint that must be paginated first to resolve `{placeholder}` in `path` (fan-out).+ parent: Optional[str] = None+ resolve_param: Optional[str] = None+ resolve_field: Optional[str] = None+ sort_mode: Literal["asc", "desc"] = "asc"+++HEX_ENDPOINTS: dict[str, HexEndpointConfig] = {+ "projects": HexEndpointConfig(+ name="projects",+ path="/v1/projects",+ data_selector="values",+ primary_keys=("id",),+ pagination="cursor",+ page_size=100,+ # createdAt never changes, so it is both a stable sort (page boundaries can't shift as+ # projects are edited mid-sync) and the partition key. Archived projects are included so+ # the table keeps the full inventory; `archivedAt` marks them.+ params={"sortBy": "CREATED_AT", "sortDirection": "ASC", "includeArchived": "true"},+ partition_key="createdAt",+ ),+ "project_runs": HexEndpointConfig(+ name="project_runs",+ path="/v1/projects/{projectId}/runs",+ data_selector="runs",+ # runId is a UUID, but runs are fetched per project, so the parent id stays in the key.+ primary_keys=("projectId", "runId"),+ pagination="offset",+ page_size=100,+ parent="projects",+ resolve_param="projectId",+ resolve_field="id",+ # GetProjectRuns has no sort param and returns run history newest-first.+ sort_mode="desc",+ # startTime is null for pending runs, so it can't be a partition key.+ ),+ "users": HexEndpointConfig(+ name="users",+ path="/v1/users",+ data_selector="values",+ primary_keys=("id",),+ pagination="cursor",+ page_size=500,+ # Email is the most stable of the two supported sort attributes (NAME, EMAIL).+ params={"sortBy": "EMAIL", "sortDirection": "ASC"},+ ),+ "groups": HexEndpointConfig(+ name="groups",+ path="/v1/groups",+ data_selector="values",+ primary_keys=("id",),+ pagination="cursor",+ page_size=500,+ params={"sortBy": "CREATED_AT", "sortDirection": "ASC"},+ ),+ "collections": HexEndpointConfig(+ name="collections",+ path="/v1/collections",+ data_selector="values",+ primary_keys=("id",),+ pagination="cursor",+ page_size=100,+ # ListCollections only supports sortBy=NAME (and no sortDirection param).+ params={"sortBy": "NAME"},+ ),+}++ENDPOINTS = tuple(HEX_ENDPOINTS.keys())++# The Hex API exposes no server-side timestamp filter on any list endpoint (ListProjects only+# filters by status/category/creator/owner/collection; GetProjectRuns only by run status and+# trigger), so every endpoint is full-refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hex/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/source.pyindex a7b0b7df8a55..1ebfa4e0ffd8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hex/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/source.py@@ -1,30 +1,140 @@-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,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.hex import HexSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.hex.hex import (+ HOST_NOT_ALLOWED_ERROR,+ HexResumeConfig,+ hex_source,+ validate_credentials as validate_hex_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hex.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class HexSource(SimpleSource[HexSourceConfig]):+class HexSource(ResumableSource[HexSourceConfig, HexResumeConfig]):+ # Hex's public API has a single, unversioned surface under /api/v1.+ api_docs_url = "https://learn.hex.tech/docs/api-integrations/api/reference"++ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.HEX+ @property+ def connection_host_fields(self) -> list[str]:+ # `workspace_url` is where the stored API token is sent; retargeting it must re-require the token.+ return ["workspace_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.HEX,category=DataWarehouseSourceCategory.ANALYTICS,label="Hex",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Hex API token to pull your Hex projects, run history, users, groups, and collections into the PostHog Data warehouse.++You can create an API token in Hex under **Workspace settings > API keys**. A personal token inherits your permissions; workspace tokens are available on some plans and can read across the workspace.++If your workspace runs on a single-tenant or self-hosted Hex deployment, enter its URL (for example `https://acme.hex.tech`). Leave it empty to use Hex's multi-tenant cloud at `app.hex.tech`.+""",iconPath="/static/services/hex.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/hex",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="workspace_url",+ label="Workspace URL (single-tenant only)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://app.hex.tech",+ secret=False,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Hex API token. Please generate a new token in your Hex workspace settings and reconnect.",+ "403 Client Error": "Your Hex API token lacks the required permissions. Please check the token's access and try again.",+ HOST_NOT_ALLOWED_ERROR: "The Hex workspace URL is not allowed. Please use your workspace's Hex URL.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.hex.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: HexSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self, config: HexSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_hex_credentials(config.workspace_url, config.api_key, schema_name, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HexResumeConfig]:+ return ResumableSourceManager[HexResumeConfig](inputs, HexResumeConfig)++ def source_for_pipeline(+ self,+ config: HexSourceConfig,+ resumable_source_manager: ResumableSourceManager[HexResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return hex_source(+ api_key=config.api_key,+ workspace_url=config.workspace_url,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ 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/hex/tests/test_hex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/tests/test_hex.pynew file mode 100644index 000000000000..516b45a2b64d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/tests/test_hex.py@@ -0,0 +1,338 @@+import json+from typing import Any, Optional++import pytest+from unittest import mock++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.hex import hex as hex_module+from products.warehouse_sources.backend.temporal.data_imports.sources.hex.hex import (+ HexResumeConfig,+ hex_source,+ normalize_workspace_host,+ validate_credentials,+)++# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+++def _response(body: dict[str, Any], *, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ return resp+++def _projects_page(ids: list[str], after: Optional[str] = None) -> Response:+ return _response(+ {+ "values": [{"id": project_id, "createdAt": "2026-01-01T00:00:00.000Z"} for project_id in ids],+ "pagination": {"after": after, "before": None},+ }+ )+++def _runs_page(runs: list[dict[str, Any]]) -> Response:+ return _response({"runs": runs, "nextPage": None, "previousPage": None, "traceId": "t"})+++def _make_manager(resume_state: Optional[HexResumeConfig] = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and capture each request's url + params AT PREPARE TIME.++ ``request.params`` is a single dict mutated in place across pages, so snapshot a copy when+ each request is prepared rather than inspecting the shared dict after the run.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {})})+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++def _source(endpoint: str = "projects", manager: Optional[mock.MagicMock] = None, workspace_url: Optional[str] = None):+ return hex_source(+ api_key="tok",+ workspace_url=workspace_url,+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager if manager is not None else _make_manager(),+ )+++class TestNormalizeWorkspaceHost:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ (None, "app.hex.tech"),+ ("", "app.hex.tech"),+ (" ", "app.hex.tech"),+ ("acme.hex.tech", "acme.hex.tech"),+ ("https://acme.hex.tech", "acme.hex.tech"),+ ("http://acme.hex.tech/", "acme.hex.tech"),+ ("acme.hex.tech/api/v1", "acme.hex.tech"),+ (" https://app.hex.tech ", "app.hex.tech"),+ ],+ )+ def test_normalize(self, raw, expected):+ assert normalize_workspace_host(raw) == expected+++class TestValidateCredentials:+ def _patch_session(self, response=None, raises=None):+ session = mock.MagicMock()+ if raises is not None:+ session.get.side_effect = raises+ else:+ session.get.return_value = response+ return mock.patch.object(hex_module, "make_tracked_session", return_value=session)++ def _resp(self, *, status_code=200, text=""):+ response = mock.MagicMock()+ response.status_code = status_code+ response.is_redirect = status_code in (301, 302, 303, 307, 308)+ response.is_permanent_redirect = status_code in (301, 308)+ response.text = text+ response.json.side_effect = Exception("not json")+ return response++ def test_success_hits_default_host(self):+ with self._patch_session(self._resp(status_code=200)) as patched:+ assert validate_credentials(None, "tok") == (True, None)+ url = patched.return_value.get.call_args.args[0]+ assert url == "https://app.hex.tech/api/v1/projects"++ def test_custom_workspace_url_is_used(self):+ with self._patch_session(self._resp(status_code=200)) as patched:+ assert validate_credentials("https://acme.hex.tech", "tok") == (True, None)+ url = patched.return_value.get.call_args.args[0]+ assert url == "https://acme.hex.tech/api/v1/projects"++ def test_invalid_token(self):+ with self._patch_session(self._resp(status_code=401)):+ assert validate_credentials(None, "tok") == (False, "Invalid Hex API token")++ def test_403_at_source_create_is_accepted(self):+ with self._patch_session(self._resp(status_code=403)):+ assert validate_credentials(None, "tok", schema_name=None) == (True, None)++ def test_403_for_scoped_probe_fails(self):+ with self._patch_session(self._resp(status_code=403)):+ valid, msg = validate_credentials(None, "tok", schema_name="projects")+ assert valid is False+ assert msg is not None++ def test_invalid_host_short_circuits(self):+ valid, msg = validate_credentials("not a host!", "tok")+ assert valid is False+ assert msg == "Invalid Hex workspace URL"++ def test_request_exception_returns_failure(self):+ import requests++ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):+ valid, msg = validate_credentials(None, "tok")+ assert valid is False+ assert "boom" in (msg or "")++ def test_rejects_redirect_response(self):+ # A workspace host that 3xx-redirects (potentially to an internal address) must be+ # rejected, not followed (SSRF).+ with self._patch_session(self._resp(status_code=302)) as patched:+ valid, msg = validate_credentials("acme.hex.tech", "tok")+ assert valid is False+ assert msg == hex_module.HOST_NOT_ALLOWED_ERROR+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False++ def test_blocks_unsafe_host(self):+ # When a team_id is supplied, a host that resolves to an internal address is rejected+ # before any HTTP request is made (SSRF guard).+ with (+ mock.patch.object(hex_module, "_is_host_safe", return_value=(False, "internal address")),+ self._patch_session(self._resp(status_code=200)) as patched,+ ):+ valid, msg = validate_credentials("10.0.0.1", "tok", team_id=99)+ assert valid is False+ assert msg == "internal address"+ patched.return_value.get.assert_not_called()+++class TestHexSourceResponse:+ @pytest.mark.parametrize(+ "endpoint, primary_keys, sort_mode",+ [+ ("projects", ["id"], "asc"),+ ("project_runs", ["projectId", "runId"], "desc"),+ ("users", ["id"], "asc"),+ ("groups", ["id"], "asc"),+ ("collections", ["id"], "asc"),+ ],+ )+ def test_response_shape(self, endpoint, primary_keys, sort_mode):+ response = _source(endpoint=endpoint)+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.sort_mode == sort_mode++ def test_projects_partitioned_on_created_at(self):+ response = _source(endpoint="projects")+ assert response.partition_keys == ["createdAt"]+ assert response.partition_mode == "datetime"++ def test_project_runs_not_partitioned(self):+ # startTime is null for pending runs, so runs can't be datetime-partitioned.+ response = _source(endpoint="project_runs")+ assert response.partition_keys is None+ assert response.partition_mode is None+++class TestHexCursorPagination:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_follows_after_cursor_across_pages(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(session, [_projects_page(["p1", "p2"], after="cur-1"), _projects_page(["p3"], after=None)])+ rows = _rows(_source())++ assert [r["id"] for r in rows] == ["p1", "p2", "p3"]+ assert snaps[0]["url"] == "https://app.hex.tech/api/v1/projects"+ assert snaps[0]["params"]["limit"] == 100+ assert snaps[0]["params"]["sortBy"] == "CREATED_AT"+ assert snaps[0]["params"]["sortDirection"] == "ASC"+ assert "after" not in snaps[0]["params"]+ assert snaps[1]["params"]["after"] == "cur-1"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_empty_page_terminates_even_with_cursor(self, MockSession):+ # An `after` token on an empty page must end pagination rather than loop forever.+ session = MockSession.return_value+ _wire(session, [_projects_page([], after="cur-1")])+ rows = _rows(_source())++ assert rows == []+ assert session.send.call_count == 1++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_state_after_yielding(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_projects_page(["p1"], after="cur-1"), _projects_page(["p2"], after=None)])+ manager = _make_manager()+ _rows(_source(manager=manager))++ manager.save_state.assert_called_once()+ saved = manager.save_state.call_args.args[0]+ assert isinstance(saved, HexResumeConfig)+ assert saved.paginator_state == {"cursor": "cur-1"}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_state(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(session, [_projects_page(["p9"], after=None)])+ manager = _make_manager(HexResumeConfig(paginator_state={"cursor": "resume-cur"}))+ rows = _rows(_source(manager=manager))++ assert snaps[0]["params"]["after"] == "resume-cur"+ assert [r["id"] for r in rows] == ["p9"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_custom_workspace_url_reaches_requests(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(session, [_projects_page(["p1"], after=None)])+ _rows(_source(workspace_url="https://acme.hex.tech"))++ assert snaps[0]["url"] == "https://acme.hex.tech/api/v1/projects"+++class TestProjectRunsFanout:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_fans_out_per_project_with_offset_pagination(self, MockSession):+ session = MockSession.return_value+ full_page = [{"runId": f"r{i}", "projectId": "p1", "status": "COMPLETED"} for i in range(100)]+ snaps = _wire(+ session,+ [+ _projects_page(["p1", "p2"], after=None),+ _runs_page(full_page),+ _runs_page([{"runId": "r100", "projectId": "p1", "status": "ERRORED"}]),+ _runs_page([{"runId": "r-b", "projectId": "p2", "status": "COMPLETED"}]),+ ],+ )+ rows = _rows(_source(endpoint="project_runs"))++ assert len(rows) == 102+ assert {r["projectId"] for r in rows} == {"p1", "p2"}+ assert snaps[0]["url"] == "https://app.hex.tech/api/v1/projects"+ assert snaps[1]["url"] == "https://app.hex.tech/api/v1/projects/p1/runs"+ assert snaps[1]["params"] == {"offset": 0, "limit": 100}+ # A full page advances the offset; a short page ends that project's pagination.+ assert snaps[2]["params"]["offset"] == 100+ assert snaps[3]["url"] == "https://app.hex.tech/api/v1/projects/p2/runs"+ assert snaps[3]["params"]["offset"] == 0++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resume_skips_completed_projects(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(+ session,+ [+ _projects_page(["p1", "p2"], after=None),+ _runs_page([{"runId": "r-b", "projectId": "p2", "status": "COMPLETED"}]),+ ],+ )+ manager = _make_manager(+ HexResumeConfig(+ paginator_state={"completed": ["/v1/projects/p1/runs"], "current": None, "child_state": None}+ )+ )+ rows = _rows(_source(endpoint="project_runs", manager=manager))++ assert [r["runId"] for r in rows] == ["r-b"]+ run_urls = [s["url"] for s in snaps[1:]]+ assert run_urls == ["https://app.hex.tech/api/v1/projects/p2/runs"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_checkpoints_completed_projects(self, MockSession):+ session = MockSession.return_value+ _wire(+ session,+ [+ _projects_page(["p1"], after=None),+ _runs_page([{"runId": "r1", "projectId": "p1", "status": "COMPLETED"}]),+ ],+ )+ manager = _make_manager()+ _rows(_source(endpoint="project_runs", manager=manager))++ final_state = manager.save_state.call_args.args[0]+ assert isinstance(final_state, HexResumeConfig)+ assert final_state.paginator_state["completed"] == ["/v1/projects/p1/runs"]+ assert final_state.paginator_state["current"] is None+++class TestRuntimeHostCheck:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_blocks_unsafe_workspace_host_before_any_request(self, MockSession):+ # The configured host is re-checked at run time (DNS rebinding) before any request.+ session = MockSession.return_value+ _wire(session, [_projects_page(["p1"], after=None)])+ with mock.patch.object(hex_module, "_is_host_safe", return_value=(False, "internal address")):+ with pytest.raises(hex_module.HexHostNotAllowedError):+ _rows(_source())+ session.send.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hex/tests/test_hex_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/tests/test_hex_source.pynew file mode 100644index 000000000000..8377500a578f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/tests/test_hex_source.py@@ -0,0 +1,105 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.hex import HexSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.hex.hex import HexResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.hex.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.hex.source import HexSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestHexSource:+ def setup_method(self):+ self.source = HexSource()+ self.team_id = 123+ self.config = HexSourceConfig(api_key="hex_token", workspace_url=None)++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.HEX++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Hex"+ assert config.label == "Hex"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/hex.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/hex"++ field_names = [f.name for f in config.fields]+ assert field_names == ["api_key", "workspace_url"]++ token_field, url_field = config.fields+ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ assert isinstance(url_field, SourceFieldInputConfig)+ assert url_field.type == SourceFieldInputConfigType.TEXT+ assert url_field.secret is False+ assert url_field.required is False++ def test_workspace_url_is_a_connection_host_field(self):+ # Retargeting the workspace URL must force re-entry of the API token — without this an+ # editor could point the stored token at a host they control.+ assert self.source.connection_host_fields == ["workspace_url"]++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_all_endpoints_full_refresh_only(self):+ # The Hex API has no server-side timestamp filter, so no endpoint may advertise+ # incremental or append sync.+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ for schema in schemas:+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["projects"])+ assert [s.name for s in schemas] == ["projects"]++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.hex.source.validate_hex_credentials")+ def test_validate_credentials_plumbs_arguments(self, mock_validate):+ mock_validate.return_value = (True, None)++ result = self.source.validate_credentials(self.config, self.team_id, schema_name="projects")++ assert result == (True, None)+ mock_validate.assert_called_once_with(self.config.workspace_url, self.config.api_key, "projects", self.team_id)++ def test_get_resumable_source_manager(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is HexResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.hex.source.hex_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_hex_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "projects"+ inputs.team_id = 42+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "ignored"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_hex_source.call_args.kwargs+ assert kwargs["api_key"] == "hex_token"+ assert kwargs["workspace_url"] is None+ assert kwargs["endpoint"] == "projects"+ assert kwargs["team_id"] == 42+ assert kwargs["job_id"] == "job-1"+ assert kwargs["resumable_source_manager"] is manager+ # Full-refresh runs must not leak a stray watermark into the transport.+ assert kwargs["db_incremental_field_last_value"] is None