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): add hyperspell users and integration channels tables (#111523)

Tom Owersee149fc20929
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 ed47fcd5e3fe..a43f81da9775 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
@@ -4202,16 +4202,16 @@ Note: docs.huntr.co is a single-page Slate reference; parsed every https://api.h
## Hyperspell — gaps
-Today (7): `connections`, `context_documents`, `entities`, `integrations`, `memories`, `queries`, `vaults`
+Today (9): `connections`, `context_documents`, `entities`, `integration_channels`, `integrations`, `memories`, `queries`, `users`, `vaults`
Diffed against: <https://docs.hyperspell.com/llms.txt>
-- [ ] `GET /users` — user roster - lookup resolving the user IDs on memories, connections and queries we already sync (high)
+- [x] `GET /users` — user roster - lookup resolving the user IDs on memories, connections and queries we already sync (high). Added as `users`.
- [ ] `GET /entities/{entity_id}/sources` — join table linking entities we sync back to the source documents they were extracted from (medium)
- [ ] `GET /connections/{connection_id}/folders` — the folder inventory per connection, needed to see what scope each connection actually indexes (medium)
-- [ ] `GET /context-documents/conflicts` — detected conflicts across context documents - the quality signal for the docs we already sync (medium)
-- [ ] `GET /context-documents/reviews` — document review records and their suggestions, the human-in-the-loop audit trail (medium)
-- [ ] `GET /integrations/{integration_id}/channels` — lookup of available channels per integration, resolving channel IDs on memories (medium)
+- [ ] `GET /context-documents/conflicts` — detected conflicts across context documents - the quality signal for the docs we already sync (medium). Skipped: not in the public OpenAPI spec (v0.32.1) or the API reference.
+- [ ] `GET /context-documents/reviews` — document review records and their suggestions, the human-in-the-loop audit trail (medium). Skipped: not in the public OpenAPI spec (v0.32.1) or the API reference.
+- [x] `GET /integrations/{integration_id}/channels` — lookup of available channels per integration, resolving channel IDs on memories (medium). Added as `integration_channels` (fan-out over each user's connections whose integration supports channel selection).
- [ ] `GET /context-documents/tree/{tree_id}/edits` — persisted user edits per document tree - edit history over synced context documents (low)
- [ ] `GET /emotional-state/recent` — time series of stored emotional-state observations (low)
- [ ] `GET /memories/status` — indexing progress per memory, useful for freshness/completeness checks (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/canonical_descriptions.py
index c7cbbae09c3f..b6941ee9e963 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/canonical_descriptions.py
@@ -101,4 +101,27 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"error": "Error message if generation failed.",
},
},
+ "users": {
+ "description": "The app's users: the distinct document owners in Hyperspell, with how many documents each owns.",
+ "docs_url": "https://docs.hyperspell.com/api-reference/users/list-users",
+ "columns": {
+ "user_id": "The user's id, valid as the X-As-User header value and matching user_id on other Hyperspell tables.",
+ "display_name": "The user's display name, when available.",
+ "document_count": "Number of documents the user owns.",
+ "last_indexed": "When a document owned by the user was last indexed.",
+ },
+ },
+ "integration_channels": {
+ "description": "Channels and chats available on each connection whose integration supports channel selection (for example Slack or Microsoft Teams), with whether each one is selected for indexing.",
+ "docs_url": "https://docs.hyperspell.com/api-reference/integrations/list-available-channels",
+ "columns": {
+ "user_id": "The Hyperspell user the connection belongs to (empty when synced app-wide without a user).",
+ "connection_id": "The connection the channel was listed through.",
+ "integration_id": "The connection's integration id.",
+ "id": "The channel's id at the provider.",
+ "name": "The channel's name.",
+ "type": "The kind of channel (for example channel, dm, or a container such as a workspace).",
+ "selected": "Whether the channel is currently selected for indexing on the connection.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/hyperspell.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/hyperspell.py
index 10ec7a1e2905..49987ea7b6ca 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/hyperspell.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/hyperspell.py
@@ -1,12 +1,13 @@
-import dataclasses
from collections.abc import Iterator
from typing import Any, Optional
-from urllib.parse import urlencode
+from urllib.parse import quote, urlencode
import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
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.common.typings import SourceResponse
@@ -31,7 +32,7 @@ class HyperspellRetryableError(Exception):
pass
+@frozen
class HyperspellResumeConfig:
# Opaque next-page cursor for the endpoint being synced. None means "start the current
# user's listing from its first page".
@@ -144,6 +145,119 @@ def _normalize_row(config: HyperspellEndpointConfig, item: dict[str, Any], user_
return row
+def _page_params(config: HyperspellEndpointConfig, cursor: str | None) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+ if config.pagination == "none":
+ return params
+ if config.page_size_param:
+ params[config.page_size_param] = config.page_size
+ if config.pagination == "offset":
+ params["offset"] = int(cursor or 0)
+ elif cursor:
+ params["cursor"] = cursor
+ return params
+
+
+def _next_cursor(
+ config: HyperspellEndpointConfig, data: dict[str, Any], items: list[dict[str, Any]], cursor: str | None
+) -> str | None:
+ if config.pagination == "cursor":
+ return data.get("next_cursor")
+ if config.pagination == "offset":
+ next_offset = int(cursor or 0) + len(items)
+ if items and next_offset < data.get("total", 0):
+ return str(next_offset)
+ return None
+
+
+def _get_list_rows(
+ session: requests.Session,
+ base_url: str,
+ config: HyperspellEndpointConfig,
+ headers: dict[str, str],
+ principal: str | None,
+ cursor: str | None,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HyperspellResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ while True:
+ url = _build_url(base_url, config.path, _page_params(config, cursor))
+
+ data = _fetch_page(session, url, headers, logger)
+ items = data.get(config.data_key) or []
+ next_cursor = _next_cursor(config, data, items, cursor)
+
+ if items:
+ yield [_normalize_row(config, item, principal) for item in items]
+
+ if not next_cursor:
+ break
+
+ # Save state AFTER yielding so a crash re-yields the last page (deduped on the
+ # primary key) rather than skipping it.
+ resumable_source_manager.save_state(HyperspellResumeConfig(cursor=next_cursor, user_id=principal))
+ cursor = next_cursor
+
+
+def _channel_integration_ids(
+ session: requests.Session, base_url: str, api_key: str, logger: FilteringBoundLogger
+) -> set[str]:
+ url = _build_url(base_url, HYPERSPELL_ENDPOINTS["integrations"].path, {})
+ integrations = _fetch_page(session, url, _get_headers(api_key), logger).get("integrations") or []
+ return {
+ integration["id"]
+ for integration in integrations
+ if integration.get("supports_channel_selection") or integration.get("requires_channel_selection")
+ }
+
+
+def _get_channel_rows(
+ session: requests.Session,
+ base_url: str,
+ config: HyperspellEndpointConfig,
+ headers: dict[str, str],
+ principal: str | None,
+ channel_integration_ids: set[str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HyperspellResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ connections_url = _build_url(base_url, HYPERSPELL_ENDPOINTS["connections"].path, {})
+ connections = _fetch_page(session, connections_url, headers, logger).get("connections") or []
+
+ for connection in connections:
+ integration_id = connection.get("integration_id")
+ if integration_id not in channel_integration_ids:
+ continue
+
+ path = config.path.format(integration_id=quote(integration_id, safe=""))
+ url = _build_url(base_url, path, {"connection_id": connection["id"]})
+ data = _fetch_page(session, url, headers, logger)
+
+ if data.get("pending"):
+ # The provider's channel list is still being walked; `channels` is empty, not real state.
+ logger.warning(f"Hyperspell: channel list pending for connection {connection['id']}, skipping")
+ resumable_source_manager.safe_point()
+ continue
+ if data.get("truncated"):
+ logger.warning(f"Hyperspell: channel list truncated for connection {connection['id']}")
+
+ channels = data.get(config.data_key) or []
+ if not channels:
+ resumable_source_manager.safe_point()
+ continue
+
+ selected = set(data.get("selected") or [])
+ yield [
+ {
+ **_normalize_row(config, channel, principal),
+ "connection_id": connection["id"],
+ "integration_id": integration_id,
+ "selected": channel.get("id") in selected,
+ }
+ for channel in channels
+ ]
+
+
def get_rows(
api_key: str,
region: str | None,
@@ -180,34 +294,30 @@ def get_rows(
resume_cursor = resume.cursor
logger.debug(f"Hyperspell: resuming {endpoint} from user_id={resume.user_id}, cursor={resume_cursor}")
+ channel_integration_ids = (
+ _channel_integration_ids(session, base_url, api_key, logger) if endpoint == "integration_channels" else set()
+ )
+
for index, principal in enumerate(remaining):
headers = _get_headers(api_key, principal)
cursor = resume_cursor
resume_cursor = None # only the resumed-into principal uses the saved cursor
- while True:
- params: dict[str, Any] = {}
- if config.paginated:
- if config.page_size_param:
- params[config.page_size_param] = config.page_size
- if cursor:
- params["cursor"] = cursor
- url = _build_url(base_url, config.path, params)
-
- data = _fetch_page(session, url, headers, logger)
- items = data.get(config.data_key) or []
- next_cursor = data.get("next_cursor") if config.paginated else None
-
- if items:
- yield [_normalize_row(config, item, principal) for item in items]
-
- if not next_cursor:
- break
-
- # Save state AFTER yielding so a crash re-yields the last page (deduped on the
- # primary key) rather than skipping it.
- resumable_source_manager.save_state(HyperspellResumeConfig(cursor=next_cursor, user_id=principal))
- cursor = next_cursor
+ if endpoint == "integration_channels":
+ yield from _get_channel_rows(
+ session,
+ base_url,
+ config,
+ headers,
+ principal,
+ channel_integration_ids,
+ logger,
+ resumable_source_manager,
+ )
+ else:
+ yield from _get_list_rows(
+ session, base_url, config, headers, principal, cursor, logger, resumable_source_manager
+ )
# Advance the bookmark to the next user so a crash between users resumes correctly.
if index + 1 < len(remaining):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/settings.py
index 7842d062172f..07833b9d785c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/settings.py
@@ -1,10 +1,12 @@
-from dataclasses import dataclass, field
-from typing import Optional
+from dataclasses import field
+from typing import Literal, Optional
+
+from posthog.dataclasses import frozen
from products.warehouse_sources.backend.types import IncrementalField
-@dataclass
+@frozen
class HyperspellEndpointConfig:
name: str
path: str
@@ -15,8 +17,9 @@ class HyperspellEndpointConfig:
# user IDs, these endpoints are fetched once per user via the X-As-User header and every
# row is stamped with a `user_id` column (empty string when querying as the app).
user_scoped: bool = False
- # Cursor-paginated endpoints return {..., "next_cursor": "..."} and accept a `cursor` param.
- paginated: bool = True
+ # "cursor": returns {..., "next_cursor": "..."} and accepts a `cursor` param.
+ # "offset": accepts `offset` and returns a `total` row count. "none": one response.
+ pagination: Literal["cursor", "offset", "none"] = "cursor"
# Query param that controls page size ("size" or "limit", varies per endpoint).
page_size_param: Optional[str] = "size"
page_size: int = 100
@@ -48,7 +51,7 @@ HYPERSPELL_ENDPOINTS: dict[str, HyperspellEndpointConfig] = {
data_key="connections",
primary_keys=["user_id", "id"],
user_scoped=True,
- paginated=False,
+ pagination="none",
),
# GET /integrations/list — app-level catalog of available integrations, not paginated.
"integrations": HyperspellEndpointConfig(
@@ -56,7 +59,7 @@ HYPERSPELL_ENDPOINTS: dict[str, HyperspellEndpointConfig] = {
path="/integrations/list",
data_key="integrations",
primary_keys=["id"],
- paginated=False,
+ pagination="none",
),
# GET /vault/list — collections of manually added documents.
"vaults": HyperspellEndpointConfig(
@@ -97,6 +100,27 @@ HYPERSPELL_ENDPOINTS: dict[str, HyperspellEndpointConfig] = {
page_size_param="limit",
partition_key="created_at",
),
+ # GET /users — the app's users (distinct document owners), app-level and offset paginated.
+ "users": HyperspellEndpointConfig(
+ name="users",
+ path="/users",
+ data_key="users",
+ primary_keys=["user_id"],
+ pagination="offset",
+ page_size_param="limit",
+ page_size=200, # /users caps `limit` at 200
+ ),
+ # GET /integrations/{integration_id}/channels?connection_id=... — fanned out over each
+ # user's connections whose integration supports channel selection. Channel ids are only
+ # unique within a provider workspace, so the connection is part of the key.
+ "integration_channels": HyperspellEndpointConfig(
+ name="integration_channels",
+ path="/integrations/{integration_id}/channels",
+ data_key="channels",
+ primary_keys=["user_id", "connection_id", "id"],
+ user_scoped=True,
+ pagination="none",
+ ),
}
ENDPOINTS = tuple(HYPERSPELL_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/tests/test_hyperspell.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/tests/test_hyperspell.py
index 869d033f5e5c..40f0e83d9bab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/tests/test_hyperspell.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/tests/test_hyperspell.py
@@ -44,6 +44,9 @@ class _StubManager:
def save_state(self, data: HyperspellResumeConfig) -> None:
self.saved.append(data)
+ def safe_point(self) -> None:
+ pass
+
def _run(
manager: _StubManager,
@@ -295,16 +298,96 @@ class TestGetRows:
[
("memories", "size=100"),
("entities", "limit=500"),
+ ("users", "limit=200"),
],
)
def test_page_size_param_varies_per_endpoint(self, endpoint, page_size_param) -> None:
manager = _StubManager()
- pages: list[dict[str, Any]] = [{"items": [], "next_cursor": None}]
+ pages: list[dict[str, Any]] = [{"items": [], "users": [], "total": 0, "next_cursor": None}]
_, mock_get = _run(manager, pages, endpoint=endpoint)
assert page_size_param in mock_get.call_args[0][0]
+ def test_users_offset_pagination_stops_at_total(self) -> None:
+ manager = _StubManager()
+ pages: list[dict[str, Any]] = [
+ {"users": [{"user_id": "u1"}, {"user_id": "u2"}], "total": 3, "limit": 2, "offset": 0},
+ {"users": [{"user_id": "u3"}], "total": 3, "limit": 2, "offset": 2},
+ ]
+
+ batches, mock_get = _run(manager, pages, endpoint="users", user_ids="user-1, user-2")
+
+ assert [[row["user_id"] for row in batch] for batch in batches] == [["u1", "u2"], ["u3"]]
+ urls = [call[0][0] for call in mock_get.call_args_list]
+ assert "offset=0" in urls[0]
+ assert "offset=2" in urls[1]
+ # Listing users needs an app-scoped credential, so configured user IDs must not fan it out.
+ assert all("X-As-User" not in call[1]["headers"] for call in mock_get.call_args_list)
+ assert manager.saved == [HyperspellResumeConfig(cursor="2", user_id=None)]
+
+ def test_resumes_users_from_saved_offset(self) -> None:
+ manager = _StubManager(resume_state=HyperspellResumeConfig(cursor="400", user_id=None))
+ pages: list[dict[str, Any]] = [{"users": [{"user_id": "u401"}], "total": 401}]
+
+ _, mock_get = _run(manager, pages, endpoint="users")
+
+ assert mock_get.call_count == 1
+ assert "offset=400" in mock_get.call_args[0][0]
+
+ def test_integration_channels_fan_out_over_channel_capable_connections(self) -> None:
+ manager = _StubManager()
+ pages: list[dict[str, Any]] = [
+ {
+ "integrations": [
+ {"id": "int-slack", "supports_channel_selection": True},
+ {"id": "int-drive", "supports_channel_selection": False},
+ {"id": "int-teams", "requires_channel_selection": True},
+ ]
+ },
+ {
+ "connections": [
+ {"id": "conn-1", "integration_id": "int-slack"},
+ {"id": "conn-2", "integration_id": "int-drive"},
+ {"id": "conn-3", "integration_id": "int-teams"},
+ ]
+ },
+ {
+ "channels": [{"id": "C1", "name": "general", "type": "channel"}, {"id": "C2", "name": "random"}],
+ "selected": ["C2"],
+ },
+ {"channels": [], "selected": [], "pending": True},
+ ]
+
+ batches, mock_get = _run(manager, pages, endpoint="integration_channels", user_ids="user-1")
+
+ urls = [call[0][0] for call in mock_get.call_args_list]
+ assert urls[2].endswith("/integrations/int-slack/channels?connection_id=conn-1")
+ assert urls[3].endswith("/integrations/int-teams/channels?connection_id=conn-3")
+ assert "X-As-User" not in mock_get.call_args_list[0][1]["headers"]
+ assert mock_get.call_args_list[2][1]["headers"]["X-As-User"] == "user-1"
+ assert batches == [
+ [
+ {
+ "id": "C1",
+ "name": "general",
+ "type": "channel",
+ "user_id": "user-1",
+ "connection_id": "conn-1",
+ "integration_id": "int-slack",
+ "selected": False,
+ },
+ {
+ "id": "C2",
+ "name": "random",
+ "user_id": "user-1",
+ "connection_id": "conn-1",
+ "integration_id": "int-slack",
+ "selected": True,
+ },
+ ]
+ ]
+
class TestHyperspellSource:
@pytest.mark.parametrize(