: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 hyperspell import source (#69620)
Tom Owersf05bbf80f454
diff --git a/frontend/public/services/hyperspell.svg b/frontend/public/services/hyperspell.svgnew file mode 100644index 000000000000..f963d0dbdbbd--- /dev/null+++ b/frontend/public/services/hyperspell.svg@@ -0,0 +1,14 @@+<svg width="120" height="120" viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg">+<style>+ path {+ fill: #252323;+ }+ @media (prefers-color-scheme: dark) {+ path { fill: #E2E2E2; }+ }+</style>+<path d="M114.707 103.015C115.445 104.293 114.983 105.803 113.9 106.543C113.483 106.829 112.974 107 112.404 107H45.4142H6.66209C4.61589 107 3.33764 104.787 4.35944 103.015L10.3945 92.5496C10.5719 92.2401 10.9021 92.051 11.2583 92.051H107.809C108.165 92.051 108.494 92.2401 108.672 92.5496L114.707 103.015Z" />+<path d="M103.116 82.9157C103.499 83.58 103.02 84.4102 102.253 84.4102H59.8178C59.1224 84.4102 58.6406 83.7173 58.8712 83.062C59.5304 81.1855 60.1209 79.2779 60.6402 77.3418C60.8085 76.7149 60.3319 76.1049 59.6831 76.1049H21.6031C20.8351 76.1049 20.3559 75.2748 20.7393 74.6105L26.2951 64.9764C26.4725 64.6669 26.8015 64.4766 27.1576 64.4766H91.9082C92.2643 64.4766 92.5933 64.6669 92.772 64.9764L103.116 82.9157Z" />+<path d="M87.2163 55.3425C87.5983 56.0069 87.1191 56.837 86.3525 56.837H63.5192C63.4273 56.837 63.3535 56.7619 63.3535 56.6699C63.3535 54.2287 63.2421 51.8134 63.0271 49.4279C62.9818 48.9177 62.5518 48.5317 62.0402 48.5317H37.5027C36.736 48.5317 36.2568 47.7016 36.6402 47.0372L41.2376 39.0636C41.415 38.7553 41.7453 38.5649 42.1014 38.5649H76.9659C77.322 38.5649 77.651 38.7553 77.8284 39.0636L87.2163 55.3425Z" />+<path d="M57.2304 11.3297C58.2535 9.55676 60.8125 9.55676 61.8356 11.3297L72.2725 29.4295C72.6558 30.0939 72.1767 30.924 71.41 30.924H59.8075C59.3814 30.924 59.0033 30.6534 58.8608 30.2506C57.4298 26.1841 55.6763 22.2678 53.634 18.5341C53.4656 18.2272 53.4682 17.8542 53.643 17.5512L57.2304 11.3297Z" />+</svg>diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex cff21f805d4a..9953857e86aa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -217,6 +217,7 @@ the row lists both.| hubspot | HTTP | requests | ✅ || hugging_face | HTTP | requests | ✅ || huntr | HTTP | requests | ✅ |+| hyperspell | HTTP | requests | ✅ || imagga | HTTP | requests | ✅ || incident_io | HTTP | requests | ✅ || inflowinventory | HTTP | requests | ✅ |@@ -610,7 +611,6 @@ doesn't conflict with concurrent PRs.- hoorayhr- hubplanner- humanitix-- hyperspell- ikas- illumina_basespace- impactdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 6ad99a4d8a58..0d1c303bdb72 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@@ -1788,7 +1788,9 @@ class HuntrSourceConfig(config.Config):@config.configclass HyperspellSourceConfig(config.Config):- pass+ api_key: str+ region: Literal["us", "eu"] = config.value(default="us")+ user_id: str | None = None@config.configdiff --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.pynew file mode 100644index 000000000000..d381037ff966--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/canonical_descriptions.py@@ -0,0 +1,94 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the official Hyperspell API reference (https://docs.hyperspell.com)+# and the published OpenAPI spec at https://api.hyperspell.com/openapi.json.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "memories": {+ "description": (+ "Every document indexed in the Hyperspell memory layer, across all connected sources "+ "(Slack, Notion, Google Drive, Gmail and more), with its indexing status and metadata."+ ),+ "docs_url": "https://docs.hyperspell.com/api-reference/memories/list-memories",+ "columns": {+ "resource_id": "Identifier of the document within its source; unique per source, not globally.",+ "source": "The provider the document was ingested from (e.g. slack, notion, google_drive, vault).",+ "type": "Hyperdoc document type discriminator (document, message, file, event, ...).",+ "title": "Human-readable document title.",+ "status": "Indexing status of the document (pending, processing, completed, failed, pending_review, skipped).",+ "collection": "The document's collection, if any.",+ "metadata": "Filterable custom metadata attached to the document.",+ "ingested_at": "When Hyperspell first indexed the document.",+ "last_modified_at": "When the source document was last modified.",+ "document_date": "The document's own date (e.g. email sent date, event date).",+ "document": "The full nested document payload (text, chunks, children).",+ },+ },+ "connections": {+ "description": "Data-source connections linked to the Hyperspell app or user (one per connected account).",+ "docs_url": "https://docs.hyperspell.com/api-reference/connections/list-connections",+ "columns": {+ "id": "Unique identifier for the connection.",+ "integration_id": "The integration this connection belongs to.",+ "provider": "The connection's provider (e.g. slack, notion, google_drive).",+ "label": "The connection's display label.",+ "selected_count": "Count of channels/workspaces selected for indexing on this connection.",+ },+ },+ "integrations": {+ "description": "The catalog of integrations available to the Hyperspell app, with their capabilities.",+ "docs_url": "https://docs.hyperspell.com/api-reference/integrations/list-all-integrations",+ "columns": {+ "id": "Unique identifier for the integration.",+ "provider": "The integration's provider.",+ "name": "The integration's display name.",+ "icon": "URL to the integration's icon.",+ "allow_multiple_connections": "Whether the integration allows multiple connections.",+ "auth_provider": "The integration's auth provider.",+ "actions_only": "Whether this integration only supports write actions (no sync).",+ "requires_channel_selection": "Whether the user must select channels before indexing starts.",+ "supports_channel_selection": "Whether the integration offers an optional channel picker to narrow indexing.",+ "channel_selection_required": "Whether an empty channel selection indexes nothing (the user must pick channels).",+ },+ },+ "entities": {+ "description": "Entities Hyperspell extracted from indexed documents (people, companies, topics, ...), app-wide.",+ "docs_url": "https://docs.hyperspell.com/api-reference/entities/list-entities",+ "columns": {+ "id": "Unique identifier for the entity.",+ "type": "The entity's type.",+ "name": "The entity's name.",+ "description": "A description of the entity, if available.",+ "attributes": "Structured attributes extracted for the entity.",+ "mention_count": "Number of documents mentioning the entity.",+ "first_seen_resource_id": "Resource id of the document the entity was first seen in.",+ "last_seen_resource_id": "Resource id of the document the entity was most recently seen in.",+ "created_at": "When the entity was first extracted.",+ "updated_at": "When the entity was last updated.",+ },+ },+ "queries": {+ "description": "The log of memory queries issued against the app, for evaluation and recall analysis.",+ "docs_url": "https://docs.hyperspell.com/api-reference/evaluation/list-prior-queries",+ "columns": {+ "query_id": "The ID of the query.",+ "user_id": "The ID of the user that issued the query, if any.",+ "time": "When the query was issued.",+ "query": "The query string that was issued.",+ },+ },+ "context_documents": {+ "description": "Context documents Hyperspell generated from the app's indexed data (summaries, digests, brains).",+ "docs_url": "https://docs.hyperspell.com/api-reference/context-documents/list-context-documents",+ "columns": {+ "document_id": "Unique identifier for the context document.",+ "status": "Generation status of the document.",+ "sources": "The source providers the document was generated from.",+ "model": "The model used to generate the document.",+ "created_at": "When generation was started.",+ "completed_at": "When generation completed, if it has.",+ "token_count": "Token count of the generated document.",+ },+ },+}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.pynew file mode 100644index 000000000000..6814554a180e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/hyperspell.py@@ -0,0 +1,189 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.settings import HYPERSPELL_ENDPOINTS++# Hyperspell runs two isolated regions with separate base URLs; API keys are only valid in+# the region they were created in, so the region is part of the source config.+REGION_BASE_URLS: dict[str, str] = {+ "us": "https://api.hyperspell.com",+ "eu": "https://api.eu.hyperspell.com",+}++# Hyperspell documents no rate limits, but we still retry transient 5xx and 429 with bounded+# exponential backoff so a blip or an undocumented throttle doesn't fail the whole sync.+_MAX_ATTEMPTS = 8+_REQUEST_TIMEOUT_SECONDS = 60++# Memory rows carry the full nested document payload (text + chunk children), so cap the+# per-chunk byte size below the batcher default to avoid materialising oversized Arrow tables.+_MEMORIES_CHUNK_SIZE_BYTES = 100 * 1024 * 1024+++class HyperspellRetryableError(Exception):+ """Raised for rate-limit (429) and transient 5xx responses so tenacity retries them."""++ pass+++class HyperspellResumeConfig:+ # The cursor used to fetch the page most recently yielded (None for the first page). On+ # resume we re-fetch this page and re-yield it (merge dedupes on the primary key) rather+ # than risk skipping rows that were batched but not yet persisted when the worker stopped.+ cursor: Optional[str] = None+++def _base_url(region: str) -> str:+ return REGION_BASE_URLS.get(region, REGION_BASE_URLS["us"])+++def _get_headers(api_key: str, user_id: Optional[str]) -> dict[str, str]:+ headers = {"Authorization": f"Bearer {api_key}"}+ if user_id:+ # Memories are per-user scoped; an app-level API key plus X-As-User reads a specific+ # user's data (equivalent to exchanging the API key for that user's token).+ headers["X-As-User"] = user_id+ return headers+++def _get_session(api_key: str, user_id: Optional[str]) -> requests.Session:+ # One session per sync so keep-alive is preserved across pages and retries. `redact_values`+ # masks the key from request telemetry/log samples, and `allow_redirects=False` keeps a+ # credentialed request pinned to the validated Hyperspell host. `capture=False` keeps the+ # arbitrary user-authored memory documents and query logs out of HTTP sample storage, since+ # the name-based scrubbers can't recognise that free-form content.+ return make_tracked_session(+ headers=_get_headers(api_key, user_id),+ redact_values=(api_key,),+ allow_redirects=False,+ capture=False,+ )+++def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{base_url}{path}"+ return f"{base_url}{path}?{urlencode(params)}"+++@retry(+ retry=retry_if_exception_type((HyperspellRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(_MAX_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> requests.Response:+ response = session.get(url, timeout=_REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise HyperspellRetryableError(f"Hyperspell API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Hyperspell API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response+++def get_rows(+ api_key: str,+ region: str,+ user_id: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HyperspellResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = HYPERSPELL_ENDPOINTS[endpoint]+ session = _get_session(api_key, user_id)+ base_url = _base_url(region)++ if not config.paginated:+ response = _fetch_page(session, _build_url(base_url, config.path, {}), logger)+ rows = response.json().get(config.data_key) or []+ if rows:+ yield rows+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor: Optional[str] = resume.cursor if resume is not None else None+ if resume is not None:+ logger.debug(f"Hyperspell: resuming {endpoint} from cursor={cursor}")++ while True:+ params: dict[str, Any] = {config.size_param: config.page_size}+ if cursor is not None:+ params["cursor"] = cursor+ response = _fetch_page(session, _build_url(base_url, config.path, params), logger)+ body = response.json()+ rows = body.get(config.data_key) or []+ if rows:+ yield rows+ resumable_source_manager.save_state(HyperspellResumeConfig(cursor=cursor))+ next_cursor = body.get("next_cursor")+ if not next_cursor:+ return+ cursor = next_cursor+++def validate_credentials(api_key: str, region: str, user_id: Optional[str]) -> tuple[bool, str | None]:+ """Confirm the key is genuine with one cheap probe against the primary listing we sync."""+ url = _build_url(_base_url(region), "/memories/list", {"size": 1})+ try:+ response = _get_session(api_key, user_id).get(url, timeout=10)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, (+ "Invalid Hyperspell API key. Please check your API key and the region it was created in, and try again."+ )+ if response.status_code == 403:+ return False, "Your Hyperspell API key does not have permission to list memories."++ try:+ body = response.json()+ message = body.get("message") if isinstance(body, dict) else response.text+ except Exception:+ message = response.text+ return False, message or response.text+++def hyperspell_source(+ api_key: str,+ region: str,+ user_id: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HyperspellResumeConfig],+) -> SourceResponse:+ config = HYPERSPELL_ENDPOINTS[endpoint]++ def items() -> Iterator[list[dict[str, Any]]]:+ return get_rows(api_key, region, user_id, endpoint, logger, resumable_source_manager)++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=config.primary_key,+ # Full refresh only — Hyperspell exposes no server-side timestamp filter — so no+ # incremental watermark depends on row order. Declared where documented, None otherwise.+ sort_mode=config.sort_mode,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ chunk_size_bytes=_MEMORIES_CHUNK_SIZE_BYTES if endpoint == "memories" else None,+ )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.pynew file mode 100644index 000000000000..0840c3f35dfc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/settings.py@@ -0,0 +1,95 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SortMode+from products.warehouse_sources.backend.types import IncrementalField+++@dataclass+class HyperspellEndpointConfig:+ name: str+ path: str+ # Response body key holding the row list (Hyperspell wraps every listing differently:+ # `items`, `documents`, `connections`, `integrations`).+ data_key: str+ primary_key: list[str]+ # Row arrival order where Hyperspell documents it ("newest first" on queries and context+ # documents), None where ordering is undocumented. Informational only today: every endpoint+ # is full-refresh, so no incremental watermark depends on it.+ sort_mode: Optional[SortMode] = None+ # Cursor-paginated endpoints take a `cursor` param and return `next_cursor` in the body.+ # Connections and integrations return the complete list in a single unpaginated response.+ paginated: bool = True+ # Hyperspell is inconsistent about the page-size param name: /memories/list and+ # /evaluate/queries take `size` (max 100), /entities and /context-documents take `limit`.+ size_param: str = "size"+ page_size: int = 100+ # Stable datetime field used for datetime partitioning, or None when the resource exposes+ # no immutable timestamp. We never partition on fields that move (e.g. updated_at,+ # last_modified_at) — only ones fixed at row creation.+ partition_key: Optional[str] = None+ # No Hyperspell list endpoint exposes a server-side updated-since/created-since filter+ # (memories only filter on source/collection/status/metadata), so every endpoint is+ # full-refresh only (empty incremental_fields).+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++HYPERSPELL_ENDPOINTS: dict[str, HyperspellEndpointConfig] = {+ "memories": HyperspellEndpointConfig(+ name="memories",+ path="/memories/list",+ data_key="items",+ # resource_id is only unique within its source provider (the read/update endpoints are+ # keyed by {source}/{resource_id}), so the composite key keeps rows unique table-wide.+ primary_key=["source", "resource_id"],+ # When Hyperspell first indexed the document — set once, never moves.+ partition_key="ingested_at",+ ),+ "connections": HyperspellEndpointConfig(+ name="connections",+ path="/connections/list",+ data_key="connections",+ primary_key=["id"],+ paginated=False,+ ),+ "integrations": HyperspellEndpointConfig(+ name="integrations",+ path="/integrations/list",+ data_key="integrations",+ primary_key=["id"],+ paginated=False,+ ),+ "entities": HyperspellEndpointConfig(+ name="entities",+ path="/entities",+ data_key="items",+ primary_key=["id"],+ size_param="limit",+ page_size=500,+ partition_key="created_at",+ ),+ "queries": HyperspellEndpointConfig(+ name="queries",+ path="/evaluate/queries",+ data_key="items",+ primary_key=["query_id"],+ sort_mode="desc",+ # `time` is when the query was issued; query log rows are immutable.+ partition_key="time",+ ),+ "context_documents": HyperspellEndpointConfig(+ name="context_documents",+ path="/context-documents",+ data_key="documents",+ primary_key=["document_id"],+ sort_mode="desc",+ size_param="limit",+ partition_key="created_at",+ ),+}++ENDPOINTS = tuple(HYPERSPELL_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in HYPERSPELL_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/source.pyindex 2c24554fbb38..9e13d20293d7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/source.py@@ -1,31 +1,163 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HyperspellSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.hyperspell import (+ HyperspellResumeConfig,+ hyperspell_source,+ validate_credentials as validate_hyperspell_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class HyperspellSource(SimpleSource[HyperspellSourceConfig]):+class HyperspellSource(ResumableSource[HyperspellSourceConfig, HyperspellResumeConfig]):+ # get_schemas iterates a static endpoint catalog with no I/O, so the table list is safe to+ # render in the public docs without credentials.+ lists_tables_without_credentials = True+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.HYPERSPELL+ @property+ def connection_host_fields(self) -> list[str]:+ # `region` picks the host the API key is sent to (api.hyperspell.com vs api.eu.hyperspell.com)+ # and `user_id` sets the `X-As-User` identity the key acts as. Changing either retargets the+ # stored key, so both must re-require the secret to be re-entered.+ return ["region", "user_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.HYPERSPELL,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Hyperspell",- iconPath="/static/services/hyperspell.png",+ caption=(+ "Sync your Hyperspell memories, connections, integrations, extracted entities, query logs "+ "and context documents. Create an API key in the **[Hyperspell dashboard](https://dashboard.hyperspell.com)** "+ "and paste it below, choosing the region the key was created in.\n\n"+ "Hyperspell data is scoped per user: set a user ID to sync that user's memories, or leave "+ "it blank to sync app-scoped data only."+ ),+ iconPath="/static/services/hyperspell.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/hyperspell",keywords=["ai", "memory", "agents", "context"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Your Hyperspell API key",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (api.hyperspell.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (api.eu.hyperspell.com)", value="eu"),+ ],+ ),+ SourceFieldInputConfig(+ name="user_id",+ label="User ID (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="Sync data for a specific user",+ secret=False,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Hyperspell API key. Please check your API key and its region, and reconnect.",+ "403 Client Error": "Your Hyperspell API key lacks the required permissions. Please check the key and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: HyperspellSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ # Hyperspell has no server-side updated-since/created-since filter on any list+ # endpoint, so every schema is full-refresh only.+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in list(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: HyperspellSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_hyperspell_credentials(config.api_key, config.region, config.user_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HyperspellResumeConfig]:+ return ResumableSourceManager[HyperspellResumeConfig](inputs, HyperspellResumeConfig)++ def source_for_pipeline(+ self,+ config: HyperspellSourceConfig,+ resumable_source_manager: ResumableSourceManager[HyperspellResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return hyperspell_source(+ api_key=config.api_key,+ region=config.region,+ user_id=config.user_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)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.pynew file mode 100644index 000000000000..1399c9cc2f64--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/tests/test_hyperspell.py@@ -0,0 +1,262 @@+from typing import Any++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.hyperspell import (+ HyperspellResumeConfig,+ HyperspellRetryableError,+ _base_url,+ _build_url,+ _fetch_page,+ _get_headers,+ get_rows,+ hyperspell_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.settings import HYPERSPELL_ENDPOINTS++_TRANSPORT = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.hyperspell.make_tracked_session"+)+++def _make_manager(resume_state: HyperspellResumeConfig | None = 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 _response(body: Any, status_code: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = status_code+ resp.ok = 200 <= status_code < 300+ return resp+++def _session_returning(*bodies: Any) -> mock.MagicMock:+ """Build a session whose successive .get() calls return the given JSON bodies."""+ session = mock.MagicMock()+ session.get.side_effect = [_response(b) for b in bodies]+ return session+++class TestHyperspellTransport:+ def test_headers_use_bearer(self):+ headers = _get_headers("abc123", None)+ assert headers["Authorization"] == "Bearer abc123"+ assert "X-As-User" not in headers++ def test_headers_add_as_user_when_user_id_given(self):+ # X-As-User scopes an app-level API key to one user's data.+ headers = _get_headers("abc123", "user-42")+ assert headers["X-As-User"] == "user-42"++ @pytest.mark.parametrize(+ "region, expected",+ [+ ("us", "https://api.hyperspell.com"),+ ("eu", "https://api.eu.hyperspell.com"),+ ("unknown", "https://api.hyperspell.com"),+ ],+ )+ def test_base_url_by_region(self, region, expected):+ assert _base_url(region) == expected++ @pytest.mark.parametrize(+ "params, expected",+ [+ ({"size": 100}, "https://api.hyperspell.com/memories/list?size=100"),+ ({}, "https://api.hyperspell.com/memories/list"),+ ],+ )+ def test_build_url(self, params, expected):+ assert _build_url("https://api.hyperspell.com", "/memories/list", params) == expected++ @pytest.mark.parametrize("status_code", [429, 500, 502, 503])+ @mock.patch("time.sleep") # neutralize tenacity's exponential backoff so retries are instant+ def test_fetch_page_retryable_statuses_raise(self, _mock_sleep, status_code):+ session = mock.MagicMock()+ session.get.return_value = _response({}, status_code=status_code)+ # reraise=True surfaces the final HyperspellRetryableError after retries are exhausted.+ with pytest.raises(HyperspellRetryableError):+ _fetch_page(session, "https://api.hyperspell.com/memories/list", mock.MagicMock())++ def test_fetch_page_client_error_raises_for_status(self):+ resp = _response({"message": "Not a valid JWT", "error": "InvalidAPIKey"}, status_code=401)+ resp.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=resp)+ session = mock.MagicMock()+ session.get.return_value = resp+ with pytest.raises(requests.HTTPError):+ _fetch_page(session, "https://api.hyperspell.com/memories/list", mock.MagicMock())++ def test_fetch_page_ok_response_returned(self):+ session = mock.MagicMock()+ session.get.return_value = _response({"items": []})+ resp = _fetch_page(session, "https://api.hyperspell.com/memories/list", mock.MagicMock())+ assert resp.json() == {"items": []}+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected_ok",+ [(200, True), (401, False), (403, False), (500, False)],+ )+ @mock.patch(_TRANSPORT)+ def test_status_mapping(self, mock_session, status_code, expected_ok):+ body: dict[str, Any] = {"items": [], "next_cursor": None} if status_code == 200 else {"message": "nope"}+ mock_session.return_value.get.return_value = _response(body, status_code=status_code)+ ok, error = validate_credentials("key", "us", None)+ assert ok is expected_ok+ if not ok:+ assert error++ @pytest.mark.parametrize(+ "region, expected_host",+ [("us", "https://api.hyperspell.com"), ("eu", "https://api.eu.hyperspell.com")],+ )+ @mock.patch(_TRANSPORT)+ def test_probes_memories_endpoint_in_region(self, mock_session, region, expected_host):+ mock_session.return_value.get.return_value = _response({"items": [], "next_cursor": None})+ validate_credentials("key", region, None)+ url = mock_session.return_value.get.call_args.args[0]+ assert url == f"{expected_host}/memories/list?size=1"++ @mock.patch(_TRANSPORT)+ def test_request_exception_is_failure(self, mock_session):+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")+ ok, error = validate_credentials("key", "us", None)+ assert ok is False+ assert "boom" in (error or "")+++class TestGetRowsPaginated:+ @mock.patch(_TRANSPORT)+ def test_follows_next_cursor_until_exhausted(self, mock_session):+ mock_session.return_value = _session_returning(+ {"items": [{"resource_id": "a"}, {"resource_id": "b"}], "next_cursor": "c1"},+ {"items": [{"resource_id": "c"}], "next_cursor": None},+ )+ manager = _make_manager()++ batches = list(get_rows("key", "us", None, "memories", mock.MagicMock(), manager))++ assert [row["resource_id"] for batch in batches for row in batch] == ["a", "b", "c"]+ urls = [c.args[0] for c in mock_session.return_value.get.call_args_list]+ assert urls[0] == "https://api.hyperspell.com/memories/list?size=100"+ assert urls[1] == "https://api.hyperspell.com/memories/list?size=100&cursor=c1"+ # State saved once per non-empty yielded page, with the cursor that fetched that page.+ saved = [c.args[0] for c in manager.save_state.call_args_list]+ assert [s.cursor for s in saved] == [None, "c1"]++ @mock.patch(_TRANSPORT)+ def test_resumes_from_saved_cursor(self, mock_session):+ mock_session.return_value = _session_returning(+ {"items": [{"resource_id": "z"}], "next_cursor": None},+ )+ manager = _make_manager(HyperspellResumeConfig(cursor="c9"))++ batches = list(get_rows("key", "us", None, "memories", mock.MagicMock(), manager))++ assert [row["resource_id"] for batch in batches for row in batch] == ["z"]+ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert "cursor=c9" in first_url++ @mock.patch(_TRANSPORT)+ def test_empty_listing_yields_nothing(self, mock_session):+ mock_session.return_value = _session_returning({"items": [], "next_cursor": None})+ manager = _make_manager()++ assert list(get_rows("key", "us", None, "memories", mock.MagicMock(), manager)) == []+ manager.save_state.assert_not_called()++ @pytest.mark.parametrize(+ "endpoint, expected_size_param",+ [("memories", "size=100"), ("entities", "limit=500"), ("context_documents", "limit=100")],+ )+ @mock.patch(_TRANSPORT)+ def test_page_size_param_per_endpoint(self, mock_session, endpoint, expected_size_param):+ # Hyperspell uses `size` on some listings and `limit` on others.+ data_key = HYPERSPELL_ENDPOINTS[endpoint].data_key+ mock_session.return_value = _session_returning({data_key: [], "next_cursor": None})+ list(get_rows("key", "us", None, endpoint, mock.MagicMock(), _make_manager()))+ url = mock_session.return_value.get.call_args.args[0]+ assert expected_size_param in url+++class TestGetRowsUnpaginated:+ @pytest.mark.parametrize("endpoint", ["connections", "integrations"])+ @mock.patch(_TRANSPORT)+ def test_single_request_without_pagination_params(self, mock_session, endpoint):+ config = HYPERSPELL_ENDPOINTS[endpoint]+ mock_session.return_value = _session_returning({config.data_key: [{"id": "x1"}, {"id": "x2"}]})+ manager = _make_manager()++ batches = list(get_rows("key", "us", None, endpoint, mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["x1", "x2"]+ assert mock_session.return_value.get.call_count == 1+ url = mock_session.return_value.get.call_args.args[0]+ assert "?" not in url++ @mock.patch(_TRANSPORT)+ def test_uses_eu_base_url(self, mock_session):+ mock_session.return_value = _session_returning({"connections": []})+ list(get_rows("key", "eu", None, "connections", mock.MagicMock(), _make_manager()))+ url = mock_session.return_value.get.call_args.args[0]+ assert url.startswith("https://api.eu.hyperspell.com/")+++class TestHyperspellSourceResponse:+ @pytest.mark.parametrize("endpoint", list(HYPERSPELL_ENDPOINTS.keys()))+ def test_source_response_shape(self, endpoint):+ config = HYPERSPELL_ENDPOINTS[endpoint]+ response = hyperspell_source("key", "us", None, endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_key+ assert response.sort_mode == config.sort_mode+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_memories_caps_chunk_byte_size(self):+ # Memory rows embed the full nested document payload, so the byte cap must be lowered.+ response = hyperspell_source("key", "us", None, "memories", mock.MagicMock(), _make_manager())+ assert response.chunk_size_bytes == 100 * 1024 * 1024+ other = hyperspell_source("key", "us", None, "connections", mock.MagicMock(), _make_manager())+ assert other.chunk_size_bytes is None++ @pytest.mark.parametrize(+ "endpoint, expected_keys",+ [+ ("memories", ["source", "resource_id"]),+ ("connections", ["id"]),+ ("queries", ["query_id"]),+ ("context_documents", ["document_id"]),+ ],+ )+ def test_primary_keys_are_unique_table_wide(self, endpoint, expected_keys):+ # memories carries a composite key: resource_id is only unique within its source provider.+ assert HYPERSPELL_ENDPOINTS[endpoint].primary_key == expected_keys++ @pytest.mark.parametrize(+ "endpoint, expected_partition",+ [+ ("memories", "ingested_at"),+ ("entities", "created_at"),+ ("queries", "time"),+ ("context_documents", "created_at"),+ ("connections", None),+ ("integrations", None),+ ],+ )+ def test_partition_keys_are_stable_creation_timestamps(self, endpoint, expected_partition):+ assert HYPERSPELL_ENDPOINTS[endpoint].partition_key == expected_partitiondiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/tests/test_hyperspell_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/tests/test_hyperspell_source.pynew file mode 100644index 000000000000..9a4d060c1dbe--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/tests/test_hyperspell_source.py@@ -0,0 +1,123 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HyperspellSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.hyperspell import (+ HyperspellResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.source import HyperspellSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestHyperspellSource:+ def setup_method(self):+ self.source = HyperspellSource()+ self.team_id = 123++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.HYPERSPELL++ def test_source_config(self):+ config = self.source.get_source_config+ assert config.label == "Hyperspell"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/hyperspell"++ def test_source_config_fields(self):+ fields = self.source.get_source_config.fields+ assert [f.name for f in fields] == ["api_key", "region", "user_id"]++ api_key = fields[0]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert api_key.type == SourceFieldInputConfigType.PASSWORD+ assert api_key.required is True+ assert api_key.secret is True++ # API keys are region-locked, so the region select must exist and default to US.+ region = fields[1]+ assert isinstance(region, SourceFieldSelectConfig)+ assert region.defaultValue == "us"+ assert {o.value for o in region.options} == {"us", "eu"}++ user_id = fields[2]+ assert isinstance(user_id, SourceFieldInputConfig)+ assert user_id.required is False+ assert user_id.secret is False++ def test_connection_host_fields_cover_region_and_user(self):+ # region picks the host the key is sent to and user_id sets the X-As-User identity, so+ # changing either must force the secret to be re-entered rather than reusing the stored key.+ assert self.source.connection_host_fields == ["region", "user_id"]++ def test_get_schemas_returns_all_endpoints_as_full_refresh(self):+ schemas = self.source.get_schemas(HyperspellSourceConfig(api_key="key"), self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # No server-side timestamp filter exists, so every schema is full-refresh only.+ assert all(not s.supports_incremental and not s.supports_append for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filters_by_names(self):+ schemas = self.source.get_schemas(+ HyperspellSourceConfig(api_key="key"), self.team_id, names=["memories", "connections"]+ )+ assert {s.name for s in schemas} == {"memories", "connections"}++ def test_lists_tables_without_credentials(self):+ # Static endpoint catalog with no I/O — the docs Supported tables section renders from it.+ assert self.source.lists_tables_without_credentials is True+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)++ @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_canonical_descriptions_cover_every_endpoint(self):+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.source.validate_hyperspell_credentials"+ )+ def test_validate_credentials_delegates_config_values(self, mock_validate):+ mock_validate.return_value = (True, None)+ config = HyperspellSourceConfig(api_key="secret-key", region="eu", user_id="user-1")+ result = self.source.validate_credentials(config, self.team_id)+ assert result == (True, None)+ mock_validate.assert_called_once_with("secret-key", "eu", "user-1")++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is HyperspellResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.source.hyperspell_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_hyperspell_source):+ config = HyperspellSourceConfig(api_key="key", region="us", user_id=None)+ manager = mock.MagicMock()+ inputs = mock.MagicMock()+ inputs.schema_name = "memories"+ inputs.logger = mock.MagicMock()++ self.source.source_for_pipeline(config, manager, inputs)++ mock_hyperspell_source.assert_called_once_with(+ api_key="key",+ region="us",+ user_id=None,+ endpoint="memories",+ logger=inputs.logger,+ resumable_source_manager=manager,+ )