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(warehouse-sources): add hex data connections, queried tables, cells, and threads tables (#111300)

Tom Owers7acbeb74f0ab
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index e9f328ce88a0..9137d65ce558 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -4032,11 +4032,13 @@ Today (5): `collections`, `groups`, `project_runs`, `projects`, `users`
Diffed against: <https://learn.hex.tech/docs/api-integrations/api/reference>
-- [ ] `ListDataConnections` — lookup table resolving the data connection ids referenced by projects and queried tables (high)
-- [ ] `GetQueriedTables` — per-project list of warehouse tables a project queries — the lineage table Hex users actually want (high)
+- [x] `ListDataConnections` — lookup table resolving the data connection ids referenced by projects and queried tables (high)
+- [x] `GetQueriedTables` — per-project list of warehouse tables a project queries — the lineage table Hex users actually want (high)
- [ ] `ListTopics` — semantic layer topic lookup, resolves topic references on semantic projects (medium)
-- [ ] `ListCells / GetCell` — the cells that make up each project we already sync, needed to analyze notebook composition (medium)
-- [ ] `ListThreads / GetThreadMessages` — Hex agent threads and their messages — a genuine event stream of analyst questions (medium)
+- [x] `ListCells` — the cells that make up each project we already sync, needed to analyze notebook composition (medium)
+- [ ] `GetCell` — skipped: returns the same cell object as `ListCells`, which the cells table already syncs (low)
+- [x] `ListThreads` — Hex agent threads (title, intent, summary, topics, feedback) — a genuine event stream of analyst questions (medium)
+- [ ] `GetThreadMessages` — skipped: rows are rendered text blocks with no stable id to key on, fetched per thread under a 30 requests per minute limit (low)
- [ ] `ListDraftGuides` — draft guides alongside the projects and collections we sync (low)
Note: learn.hex.tech renders the reference client-side from Docusaurus; the operation list above was parsed out of the page's rendered headings (operation ids), not from a raw OpenAPI file — Hex does not publish one at a guessable URL. GetProjectRuns, ListProjects, ListUsers, ListGroups and ListCollections are already covered.
diff --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.py
index ab9bbf15176a..74847b143c80 100644
--- 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.py
@@ -75,4 +75,73 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"sharing": "Sharing configuration for the collection (users, groups, and workspace access).",
},
},
+ "data_connections": {
+ "description": "A data connection in the Hex workspace that links Hex to a warehouse or database.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique ID for the data connection.",
+ "name": "Name of the data connection.",
+ "type": "Type of warehouse or database (e.g. snowflake, bigquery, postgres).",
+ "description": "Description of the data connection, if set.",
+ "sensitivity": "Whether the data connection is marked as sensitive, and its effective sensitivity.",
+ "connectionDetails": "Non-secret connection settings for the warehouse type, such as host, database, and username.",
+ "connectViaSsh": "Whether the connection goes through an SSH tunnel.",
+ "includeMagic": "Whether Hex Magic AI features can use this connection.",
+ "allowWritebackCells": "Whether writeback cells can write to this connection.",
+ "schemaFilters": "Filters that limit which databases, schemas, and tables Hex browses.",
+ "schemaRefreshSchedule": "Schedule for refreshing the connection's schema browser.",
+ "schemaRefreshAccess": "Who can refresh the connection's schema (ADMINS or USERS_WITH_QUERY_ACCESS).",
+ "sharing": "Sharing configuration for the data connection (users, groups, and workspace access).",
+ },
+ },
+ "queried_tables": {
+ "description": "A warehouse table that a Hex project queries, with the data connection it uses.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "projectId": "UUID of the Hex project that queries the table.",
+ "dataConnectionId": "ID of the data connection the table is queried through.",
+ "dataConnectionName": "Name of the data connection the table is queried through.",
+ "tableName": "Name of the queried warehouse table.",
+ },
+ },
+ "cells": {
+ "description": "A cell in the draft version of a Hex project, with its type and its code, SQL, or markdown contents.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique ID for the cell.",
+ "staticId": "ID of the cell that stays the same across project versions.",
+ "projectId": "UUID of the Hex project the cell belongs to.",
+ "cellType": "Type of the cell (e.g. CODE, SQL, MARKDOWN, CHART, INPUT).",
+ "label": "Label of the cell, if set.",
+ "dataConnectionId": "ID of the data connection a SQL cell queries, if any.",
+ "contents": "Source of the cell: code, SQL (with its output dataframe name), or markdown.",
+ },
+ },
+ "threads": {
+ "description": "A Hex agent thread, where a user asks the Hex agent a question or gives it a task.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique ID for the thread.",
+ "orgId": "ID of the Hex workspace the thread belongs to.",
+ "url": "URL to open the thread in Hex.",
+ "title": "Title of the thread. Null for private threads.",
+ "userId": "ID of the user who created the thread.",
+ "type": "Type of agent thread.",
+ "classification": "How the thread's work was classified (e.g. Analysis, App building), if classified.",
+ "source": "Where the thread was created (e.g. Hex, Slack, MCP, or the public API).",
+ "threadSummary": "Summary of the thread, if generated.",
+ "threadIntent": "Intent of the thread, if generated.",
+ "topics": "Semantic topics the thread used.",
+ "warnings": "Warnings Hex raised about the thread's answer.",
+ "warningsGeneratedAt": "UTC timestamp of when the warnings were generated.",
+ "feedback": "User feedback on the thread.",
+ "creditsUsed": "Total credits the thread used.",
+ "auto": "Whether the thread runs on Auto model selection.",
+ "effectiveModel": "Model the thread runs on.",
+ "effortLevel": "Effort level of the thread.",
+ "sensitive": "Whether the thread is marked as sensitive.",
+ "createdAt": "UTC timestamp of when the thread was created.",
+ "updatedAt": "UTC timestamp of when the thread was last updated.",
+ },
+ },
}
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.py
index 77d64d91979a..8afc490fc91c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hex/hex.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/hex.py
@@ -12,6 +12,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
rest_api_resource,
rest_api_resources,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ rename_parent_fields,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
JSONResponseCursorPaginator,
OffsetPaginator,
@@ -35,11 +38,11 @@ class HexHostNotAllowedError(Exception):
pass
[email protected](frozen=True)
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.
+ # for per-project endpoints.
paginator_state: dict[str, Any]
@@ -162,6 +165,9 @@ def _endpoint_resource(config: HexEndpointConfig) -> EndpointResource:
},
"table_format": "delta",
}
+ if config.parent is not None and config.include_from_parent:
+ resource["include_from_parent"] = list(config.include_from_parent)
+ resource["data_map"] = rename_parent_fields(config.parent, config.include_from_parent)
return resource
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.py
index 1069a6df9de0..194c00061b0e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hex/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hex/settings.py
@@ -23,6 +23,8 @@ class HexEndpointConfig:
parent: Optional[str] = None
resolve_param: Optional[str] = None
resolve_field: Optional[str] = None
+ # Parent fields copied onto each child row, as `{parent field: child column}`.
+ include_from_parent: dict[str, str] = field(default_factory=dict)
sort_mode: Literal["asc", "desc"] = "asc"
@@ -84,11 +86,59 @@ HEX_ENDPOINTS: dict[str, HexEndpointConfig] = {
# ListCollections only supports sortBy=NAME (and no sortDirection param).
params={"sortBy": "NAME"},
),
+ "data_connections": HexEndpointConfig(
+ name="data_connections",
+ path="/v1/data-connections",
+ data_selector="values",
+ primary_keys=("id",),
+ pagination="cursor",
+ page_size=100,
+ # createdAt is not returned, but it is the stable sort of the two supported (NAME, CREATED_AT).
+ params={"sortBy": "CREATED_AT", "sortDirection": "ASC"},
+ ),
+ "queried_tables": HexEndpointConfig(
+ name="queried_tables",
+ path="/v1/projects/{projectId}/queriedTables",
+ data_selector="values",
+ # Rows carry no project id, so it is injected from the parent to keep the key table-wide unique.
+ primary_keys=("projectId", "dataConnectionId", "tableName"),
+ pagination="cursor",
+ page_size=100,
+ parent="projects",
+ resolve_param="projectId",
+ resolve_field="id",
+ include_from_parent={"id": "projectId"},
+ ),
+ "cells": HexEndpointConfig(
+ name="cells",
+ # ListCells takes the project as a required query param, which the framework can only
+ # resolve from the path.
+ path="/v1/cells?projectId={projectId}",
+ data_selector="values",
+ primary_keys=("projectId", "id"),
+ pagination="cursor",
+ page_size=100,
+ parent="projects",
+ resolve_param="projectId",
+ resolve_field="id",
+ ),
+ "threads": HexEndpointConfig(
+ name="threads",
+ path="/v1/threads",
+ data_selector="threads",
+ primary_keys=("id",),
+ pagination="cursor",
+ page_size=100,
+ # ListThreads has no sort param and returns the newest threads first.
+ sort_mode="desc",
+ partition_key="createdAt",
+ ),
}
ENDPOINTS = tuple(HEX_ENDPOINTS.keys())
-# The Hex API exposes no server-side timestamp filter on any list endpoint (ListProjects only
+# The Hex API exposes no usable 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.
+# trigger; ListThreads' `numDays` bounds whole days of creation, but threads keep changing after
+# that), 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.py
index d397fe93d5c1..beda4dc840ed 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
@@ -52,9 +52,9 @@ class HexSource(ResumableSource[HexSourceConfig, HexResumeConfig]):
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.
+ caption="""Enter your Hex API token to pull your Hex projects, run history, cells, queried tables, data connections, agent threads, 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.
+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. The threads table needs a token from a user with the Manager role or higher.
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`.
""",
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.py
index 516b45a2b64d..0f39271f625e 100644
--- 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.py
@@ -326,6 +326,58 @@ class TestProjectRunsFanout:
assert final_state.paginator_state["current"] is None
+class TestPerProjectCursorFanout:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_queried_tables_follow_child_cursor_and_carry_project_id(self, MockSession):
+ session = MockSession.return_value
+
+ def _tables_page(names: list[str], after: Optional[str] = None) -> Response:
+ return _response(
+ {
+ "values": [
+ {"dataConnectionId": "dc1", "dataConnectionName": "Warehouse", "tableName": name}
+ for name in names
+ ],
+ "pagination": {"after": after, "before": None},
+ "traceId": "t",
+ }
+ )
+
+ snaps = _wire(
+ session,
+ [
+ _projects_page(["p1", "p2"], after=None),
+ _tables_page(["orders"], after="cur-1"),
+ _tables_page(["users"], after=None),
+ _tables_page(["orders"], after=None),
+ ],
+ )
+ rows = _rows(_source(endpoint="queried_tables"))
+
+ assert [(r["projectId"], r["tableName"]) for r in rows] == [("p1", "orders"), ("p1", "users"), ("p2", "orders")]
+ assert all("_projects_id" not in r for r in rows)
+ assert snaps[1]["url"] == "https://app.hex.tech/api/v1/projects/p1/queriedTables"
+ assert snaps[2]["params"]["after"] == "cur-1"
+ assert snaps[3]["url"] == "https://app.hex.tech/api/v1/projects/p2/queriedTables"
+ assert "after" not in snaps[3]["params"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_cells_pass_project_as_query_param(self, MockSession):
+ session = MockSession.return_value
+ snaps = _wire(
+ session,
+ [
+ _projects_page(["p1"], after=None),
+ _response({"values": [{"id": "c1", "projectId": "p1"}], "pagination": {"after": None, "before": None}}),
+ ],
+ )
+ rows = _rows(_source(endpoint="cells"))
+
+ assert [r["id"] for r in rows] == ["c1"]
+ assert snaps[1]["url"] == "https://app.hex.tech/api/v1/cells?projectId=p1"
+ assert snaps[1]["params"] == {"limit": 100}
+
+
class TestRuntimeHostCheck:
@mock.patch(CLIENT_SESSION_PATCH)
def test_blocks_unsafe_workspace_host_before_any_request(self, MockSession):