: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 (#70719)
Tom Owersc639562d429c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 784335a3eebd..ad51dc798432 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@@ -1987,7 +1987,7 @@ class HuntrSourceConfig(config.Config):class HyperspellSourceConfig(config.Config):api_key: strregion: Literal["us", "eu"] = config.value(default="us")- user_id: str | None = None+ user_ids: 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.pyindex d381037ff966..c7cbbae09c3f 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@@ -1,20 +1,18 @@+# Descriptions sourced from the Hyperspell OpenAPI spec (https://api.hyperspell.com/openapi.json)+# and API docs (https://docs.hyperspell.com/).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",+ "description": "Documents indexed in Hyperspell's memory layer, ingested from connected sources (Slack, Notion, Gmail, Google Drive, and more) or added directly via the API.",+ "docs_url": "https://docs.hyperspell.com/","columns": {- "resource_id": "Identifier of the document within its source; unique per source, not globally.",+ "user_id": "The Hyperspell user the memory belongs to (empty when synced app-wide without a user).",+ "resource_id": "Identifier of the document within its source.","source": "The provider the document was ingested from (e.g. slack, notion, google_drive, vault).",- "type": "Hyperdoc document type discriminator (document, message, file, event, ...).",+ "type": "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.",@@ -22,25 +20,26 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"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",+ "description": "Data-source connections users (or the app) have authorized, linking an integration like Slack or Google Drive to Hyperspell for indexing.",+ "docs_url": "https://docs.hyperspell.com/","columns": {- "id": "Unique identifier for the connection.",- "integration_id": "The integration this connection belongs to.",+ "user_id": "The Hyperspell user the connection belongs to (empty when synced app-wide without a user).",+ "id": "The connection's id.",+ "integration_id": "The connection's integration id.","provider": "The connection's provider (e.g. slack, notion, google_drive).",- "label": "The connection's display label.",+ "label": "The connection's label.","selected_count": "Count of channels/workspaces selected for indexing on this connection.",+ "scope": "'user' for a personal connection; 'app' for an org-wide connection shared with every user of the app.",},},"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",+ "description": "The catalog of integrations available to the app, with each integration's auth provider and selection requirements.",+ "docs_url": "https://docs.hyperspell.com/","columns": {- "id": "Unique identifier for the integration.",+ "id": "The integration's id.","provider": "The integration's provider.","name": "The integration's display name.","icon": "URL to the integration's icon.",@@ -49,28 +48,38 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"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).",+ "supports_folder_selection": "Whether the integration supports per-folder sync policies.",+ },+ },+ "vaults": {+ "description": "Vault collections of manually added documents, with the number of documents in each.",+ "docs_url": "https://docs.hyperspell.com/",+ "columns": {+ "user_id": "The Hyperspell user the vault belongs to (empty when synced app-wide without a user).",+ "collection": "The collection's name (empty string for the default vault).",+ "document_count": "Number of documents in the collection.",},},"entities": {- "description": "Entities Hyperspell extracted from indexed documents (people, companies, topics, ...), app-wide.",- "docs_url": "https://docs.hyperspell.com/api-reference/entities/list-entities",+ "description": "Entities (people, companies, projects, ...) extracted from indexed memories, with mention counts and attributes.",+ "docs_url": "https://docs.hyperspell.com/","columns": {- "id": "Unique identifier for the entity.",+ "user_id": "The Hyperspell user the entity was extracted for (empty when synced app-wide without a user).",+ "id": "Unique identifier of the entity.","type": "The entity's type.","name": "The entity's name.",- "description": "A description of the entity, if available.",+ "description": "Description of the entity.","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.",+ "mention_count": "How many times the entity is mentioned across indexed documents.",+ "first_seen_resource_id": "Resource where the entity was first seen.",+ "last_seen_resource_id": "Resource where the entity was most recently seen.","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",+ "description": "Prior queries issued against the app's memory index, useful for evaluating recall quality.",+ "docs_url": "https://docs.hyperspell.com/","columns": {"query_id": "The ID of the query.","user_id": "The ID of the user that issued the query, if any.",@@ -79,16 +88,17 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {},},"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",+ "description": "Context documents generated by Hyperspell for the app, summarizing indexed knowledge.",+ "docs_url": "https://docs.hyperspell.com/","columns": {- "document_id": "Unique identifier for the context document.",+ "document_id": "Unique identifier of the context document.","status": "Generation status of the document.",- "sources": "The source providers the document was generated from.",+ "sources": "The sources 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.",+ "created_at": "When generation was requested.",+ "completed_at": "When generation completed.","token_count": "Token count of the generated document.",+ "error": "Error message if generation failed.",},},}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.pyindex 6814554a180e..a96bec07c380 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@@ -10,180 +10,235 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom 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+from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.settings import (+ HYPERSPELL_ENDPOINTS,+ HyperspellEndpointConfig,+)-# 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] = {+# Hyperspell runs two isolated regions; API keys are only valid in the region they were+# created in, so the base URL is a source config option.+HYPERSPELL_BASE_URLS: dict[str, str] = {"us": "https://api.hyperspell.com","eu": "https://api.eu.hyperspell.com",}+DEFAULT_REGION = "us"-# 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+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 5class HyperspellRetryableError(Exception):- """Raised for rate-limit (429) and transient 5xx responses so tenacity retries them."""-pass@dataclasses.dataclassclass 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}"}+ # Opaque next-page cursor for the endpoint being synced. None means "start the current+ # user's listing from its first page".+ cursor: str | None = None+ # The user (X-As-User value) currently being fanned out over. A stable user-ID bookmark+ # (not a positional index) so a config edit between a crash and the retry can't resume+ # into the wrong user. None when querying as the app.+ user_id: str | None = None+++def get_base_url(region: str | None) -> str:+ return HYPERSPELL_BASE_URLS.get((region or DEFAULT_REGION).strip().lower(), HYPERSPELL_BASE_URLS[DEFAULT_REGION])+++def parse_user_ids(raw: str | None) -> list[str]:+ """Split the comma-separated user IDs field into a deduplicated, order-preserving list."""+ if not raw:+ return []+ seen: set[str] = set()+ user_ids: list[str] = []+ for part in raw.replace("\n", ",").split(","):+ user_id = part.strip()+ if user_id and user_id not in seen:+ seen.add(user_id)+ user_ids.append(user_id)+ return user_ids+++def _get_headers(api_key: str, user_id: str | None = None) -> dict[str, str]:+ headers = {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }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).+ # Memories and connections are per-user; X-As-User scopes an API-key request to one user.headers["X-As-User"] = user_idreturn 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:+ url = f"{base_url}{path}"+ if params:+ url = f"{url}?{urlencode(params)}"+ return url+++def validate_credentials(+ api_key: str, region: str | None, schema_name: Optional[str] = None+) -> tuple[bool, str | None]:+ """Probe /integrations/list to confirm the API key is genuine.++ It's the cheapest app-level endpoint that works with a bare API key (no user context),+ so it validates the key without depending on which streams the team will sync.+ Hyperspell keys have no per-endpoint scopes, so one probe covers every schema.+ """+ url = _build_url(get_base_url(region), HYPERSPELL_ENDPOINTS["integrations"].path, {})+ try:+ response = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False).get(+ url, headers=_get_headers(api_key), timeout=REQUEST_TIMEOUT_SECONDS+ )+ except Exception:+ return False, "Could not reach the Hyperspell API. Please try again."+ if response.status_code == 200:+ return True, None+ # 401 = invalid key ("InvalidAPIKey"), 403 = missing auth ("Not authenticated"). Keys are+ # region-bound, so a valid key sent to the wrong region also surfaces as a 401.+ if response.status_code in (401, 403):+ return (+ False,+ "Invalid Hyperspell API key. Keys are region-specific, so check that the key matches the selected region.",+ )-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)}"+ return False, f"Hyperspell API returned an unexpected status code: {response.status_code}"@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),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),reraise=True,)-def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> requests.Response:- response = session.get(url, timeout=_REQUEST_TIMEOUT_SECONDS)+def _fetch_page(+ session: requests.Session, page_url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)+ # Rate limits aren't documented; treat 429 and transient 5xx as retryable with backoff.if response.status_code == 429 or response.status_code >= 500:- raise HyperspellRetryableError(f"Hyperspell API error (retryable): status={response.status_code}, url={url}")+ raise HyperspellRetryableError(+ f"Hyperspell API error (retryable): status={response.status_code}, url={page_url}"+ )if not response.ok:- logger.error(f"Hyperspell API error: status={response.status_code}, body={response.text}, url={url}")+ logger.error(f"Hyperspell API error: status={response.status_code}, body={response.text}, url={page_url}")response.raise_for_status()- return response+ return response.json()+++def _normalize_row(config: HyperspellEndpointConfig, item: dict[str, Any], user_id: str | None) -> dict[str, Any]:+ row = dict(item)+ for key, default in config.null_key_defaults.items():+ if row.get(key) is None:+ row[key] = default+ if config.user_scoped:+ # Stamp the acting user on every row — the API responses don't carry it, and it's part+ # of the primary key so rows from different users can't collide. Empty string = app scope.+ row["user_id"] = user_id or ""+ return rowdef get_rows(api_key: str,- region: str,- user_id: Optional[str],+ region: str | None,+ user_ids: str | None,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-+ base_url = get_base_url(region)+ # One session reused across every page (and every user) so urllib3 keeps the connection+ # alive instead of re-handshaking per request. capture=False keeps user-authored imported+ # content (memories, entities, context docs) out of HTTP sample storage — the name-based+ # scrubbers can't recognise it, and it lives outside the warehouse tables' access controls.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False)++ # Memories/connections are per-user, so user-scoped endpoints fan out over the configured+ # user IDs via X-As-User. With no user IDs configured (or for app-level endpoints) we make+ # a single pass as the app (principal None).+ principals: list[str | None] = [None]+ if config.user_scoped:+ configured = parse_user_ids(user_ids)+ if configured:+ principals = list(configured)++ # Resolve the saved user-ID bookmark to the slice of principals still to process. If the+ # bookmarked user was removed from the config between runs, start over from the first+ # principal. `resume_cursor` is consumed by the first principal only.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+ remaining = principals+ resume_cursor: str | None = None+ if resume is not None and resume.user_id in principals:+ remaining = principals[principals.index(resume.user_id) :]+ resume_cursor = resume.cursor+ logger.debug(f"Hyperspell: resuming {endpoint} from user_id={resume.user_id}, cursor={resume_cursor}")++ 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++ # Advance the bookmark to the next user so a crash between users resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(HyperspellResumeConfig(cursor=None, user_id=remaining[index + 1]))def hyperspell_source(api_key: str,- region: str,- user_id: Optional[str],+ region: str | None,+ user_ids: str | None,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,+ items=lambda: get_rows(+ api_key=api_key,+ region=region,+ user_ids=user_ids,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ # Hyperspell's list endpoints expose no sort parameter and pagination is driven by an+ # opaque cursor, so row ordering is undefined — never declare "asc" for undefined order.+ sort_mode="desc",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.pyindex 0840c3f35dfc..7842d062172f 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,7 +1,6 @@from dataclasses import dataclass, fieldfrom typing import Optional-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SortModefrom products.warehouse_sources.backend.types import IncrementalField@@ -9,87 +8,98 @@ from products.warehouse_sources.backend.types import IncrementalFieldclass HyperspellEndpointConfig:name: strpath: str- # Response body key holding the row list (Hyperspell wraps every listing differently:- # `items`, `documents`, `connections`, `integrations`).+ # Key that wraps the list of rows in the JSON response body (e.g. {"items": [...]}).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.+ primary_keys: list[str]+ # Endpoints whose data is scoped to a Hyperspell user. When the source is configured with+ # 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- # 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"+ # Query param that controls page size ("size" or "limit", varies per endpoint).+ page_size_param: Optional[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.+ # Stable datetime field to partition on. Never use a field that changes after 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)+ # Nullable fields that participate in the primary key, mapped to the value that replaces+ # null so merged/deduped rows keep a non-null key.+ null_key_defaults: dict[str, str] = field(default_factory=dict)+# Hyperspell's list endpoints expose no server-side timestamp filter (the /memories/list+# `filter` param only matches custom metadata), so every endpoint is full refresh only.HYPERSPELL_ENDPOINTS: dict[str, HyperspellEndpointConfig] = {+ # https://api.hyperspell.com/openapi.json — GET /memories/list"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",+ # resource_id is unique per source provider (memories are addressed as+ # /{source}/{resource_id}), and per user when fanning out over users.+ primary_keys=["user_id", "source", "resource_id"],+ user_scoped=True,+ # No partition key: the only stable timestamp (ingested_at) is nullable.),+ # GET /connections/list — not paginated, returns every connection in one response."connections": HyperspellEndpointConfig(name="connections",path="/connections/list",data_key="connections",- primary_key=["id"],+ primary_keys=["user_id", "id"],+ user_scoped=True,paginated=False,),+ # GET /integrations/list — app-level catalog of available integrations, not paginated."integrations": HyperspellEndpointConfig(name="integrations",path="/integrations/list",data_key="integrations",- primary_key=["id"],+ primary_keys=["id"],paginated=False,),+ # GET /vault/list — collections of manually added documents.+ "vaults": HyperspellEndpointConfig(+ name="vaults",+ path="/vault/list",+ data_key="items",+ primary_keys=["user_id", "collection"],+ user_scoped=True,+ # A null collection is the user's default vault; keep the key non-null.+ null_key_defaults={"collection": ""},+ ),+ # GET /entities — entities extracted from indexed memories."entities": HyperspellEndpointConfig(name="entities",path="/entities",data_key="items",- primary_key=["id"],- size_param="limit",- page_size=500,+ primary_keys=["user_id", "id"],+ user_scoped=True,+ page_size_param="limit",+ page_size=500, # /entities caps `limit` at 500 (other endpoints cap `size` at 100)partition_key="created_at",),+ # GET /evaluate/queries — prior queries issued against the app (rows carry their own+ # user_id, so the listing is app-level and query_id is unique app-wide)."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.+ primary_keys=["query_id"],partition_key="time",),+ # GET /context-documents — generated context documents for the authenticated app."context_documents": HyperspellEndpointConfig(name="context_documents",path="/context-documents",data_key="documents",- primary_key=["document_id"],- sort_mode="desc",- size_param="limit",+ primary_keys=["document_id"],+ page_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()-}+# No endpoint exposes a server-side timestamp filter, so nothing is advertised as incremental.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in HYPERSPELL_ENDPOINTS}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 9e13d20293d7..055513c332d2 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@@ -30,16 +30,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell)from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.settings import (ENDPOINTS,- INCREMENTAL_FIELDS,+ HYPERSPELL_ENDPOINTS,)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass 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+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs@propertydef source_type(self) -> ExternalDataSourceType:@@ -47,10 +45,12 @@ class HyperspellSource(ResumableSource[HyperspellSourceConfig, HyperspellResumeC@propertydef 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"]+ # The stored API key is sent to the host derived from `region`, so retargeting the+ # region must re-require the key rather than reusing it against a different host.+ # `user_ids` is the upstream identity the key acts as (via X-As-User); changing it+ # must also re-require the key so an editor without the credential can't retarget the+ # stored key at other users' data.+ return ["region", "user_ids"]@propertydef get_source_config(self) -> SourceConfig:@@ -58,17 +58,16 @@ class HyperspellSource(ResumableSource[HyperspellSourceConfig, HyperspellResumeCname=SchemaExternalDataSourceType.HYPERSPELL,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Hyperspell",- 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."- ),+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Hyperspell API key to pull your app's memories, connections, and extracted entities into the PostHog Data warehouse.++Create an API key in the [Hyperspell dashboard](https://app.hyperspell.com/). Keys are region-specific, so pick the region your Hyperspell app lives in.++Memories and connections are scoped to individual users of your Hyperspell app. To sync them, list the user IDs to sync as a comma-separated list — each is fetched via Hyperspell's `X-As-User` header. Leaving it empty syncs app-level data only.+""",iconPath="/static/services/hyperspell.svg",docsUrl="https://posthog.com/docs/cdp/sources/hyperspell",keywords=["ai", "memory", "agents", "context"],- releaseStatus=ReleaseStatus.ALPHA,fields=cast(list[FieldType],[@@ -77,7 +76,7 @@ class HyperspellSource(ResumableSource[HyperspellSourceConfig, HyperspellResumeClabel="API key",type=SourceFieldInputConfigType.PASSWORD,required=True,- placeholder="Your Hyperspell API key",+ placeholder="",secret=True,),SourceFieldSelectConfig(@@ -91,25 +90,19 @@ class HyperspellSource(ResumableSource[HyperspellSourceConfig, HyperspellResumeC],),SourceFieldInputConfig(- name="user_id",- label="User ID (optional)",+ name="user_ids",+ label="User IDs (optional)",type=SourceFieldInputConfigType.TEXT,required=False,- placeholder="Sync data for a specific user",+ placeholder="user-1, user-2",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 (+ from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.canonical_descriptions import ( # noqa: PLC0415CANONICAL_DESCRIPTIONS,)@@ -123,16 +116,17 @@ class HyperspellSource(ResumableSource[HyperspellSourceConfig, HyperspellResumeCnames: list[str] | None = None,force_refresh: bool = False,) -> list[SourceSchema]:+ # No Hyperspell list endpoint exposes a server-side timestamp filter, so every+ # table is full refresh only.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, []),+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ detected_primary_keys=HYPERSPELL_ENDPOINTS[endpoint].primary_keys,)- for endpoint in list(ENDPOINTS)+ for endpoint in ENDPOINTS]if names is not None:names_set = set(names)@@ -142,7 +136,13 @@ class HyperspellSource(ResumableSource[HyperspellSourceConfig, HyperspellResumeCdef 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)+ return validate_hyperspell_credentials(config.api_key, config.region, schema_name)++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized": "Your Hyperspell API key is invalid, expired, or for a different region. Please check the key and region, then reconnect.",+ "403 Client Error: Forbidden": "Your Hyperspell API key was not accepted. Please generate a new key in the Hyperspell dashboard and reconnect.",+ }def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HyperspellResumeConfig]:return ResumableSourceManager[HyperspellResumeConfig](inputs, HyperspellResumeConfig)@@ -156,7 +156,7 @@ class HyperspellSource(ResumableSource[HyperspellSourceConfig, HyperspellResumeCreturn hyperspell_source(api_key=config.api_key,region=config.region,- user_id=config.user_id,+ user_ids=config.user_ids,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.pyindex 1399c9cc2f64..869d033f5e5c 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@@ -1,262 +1,358 @@-from typing import Any+import json+from typing import Any, Optionalimport pytestfrom unittest import mock-import requests+import structlogfrom products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.hyperspell import (+ HYPERSPELL_BASE_URLS,HyperspellResumeConfig,- HyperspellRetryableError,- _base_url,- _build_url,- _fetch_page,- _get_headers,+ get_base_url,get_rows,hyperspell_source,+ parse_user_ids,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+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.hyperspell"-def _response(body: Any, status_code: int = 200) -> mock.MagicMock:+def _response(status: int = 200, body: Optional[dict[str, Any]] = None) -> mock.MagicMock:resp = mock.MagicMock()- resp.json.return_value = body- resp.status_code = status_code- resp.ok = 200 <= status_code < 300+ resp.status_code = status+ resp.ok = 200 <= status < 300+ resp.json.return_value = body or {}+ resp.text = json.dumps(body or {})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 _StubManager:+ """Minimal stand-in for ResumableSourceManager that records saved state."""++ def __init__(self, resume_state: Optional[HyperspellResumeConfig] = None) -> None:+ self._resume_state = resume_state+ self.saved: list[HyperspellResumeConfig] = []++ def can_resume(self) -> bool:+ return self._resume_state is not None++ def load_state(self) -> Optional[HyperspellResumeConfig]:+ return self._resume_state++ def save_state(self, data: HyperspellResumeConfig) -> None:+ self.saved.append(data)+++def _run(+ manager: _StubManager,+ pages: list[dict[str, Any]],+ endpoint: str = "memories",+ user_ids: str | None = None,+ region: str | None = "us",+) -> tuple[list[list[dict[str, Any]]], mock.MagicMock]:+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = [_response(200, page) for page in pages]+ batches = list(+ get_rows(+ api_key="hs_test",+ region=region,+ user_ids=user_ids,+ endpoint=endpoint,+ logger=structlog.get_logger(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ )+ )+ return batches, mock_session.return_value.get-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+class TestSessionPrivacy:+ def test_validate_credentials_disables_sample_capture(self) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200)++ validate_credentials("hs_test", "us")++ assert mock_session.call_args.kwargs["capture"] is False++ def test_get_rows_disables_sample_capture(self) -> None:+ manager = _StubManager()+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200, {"items": [], "next_cursor": None})++ list(+ get_rows(+ api_key="hs_test",+ region="us",+ user_ids=None,+ endpoint="memories",+ logger=structlog.get_logger(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ )+ )- 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"+ # Imported memory content is user-authored (Gmail, Slack, Notion, ...) and lives outside+ # the warehouse tables' access controls, so it must never reach HTTP sample storage.+ assert mock_session.call_args.kwargs["capture"] is False++class TestGetBaseUrl:@pytest.mark.parametrize("region, expected",[- ("us", "https://api.hyperspell.com"),- ("eu", "https://api.eu.hyperspell.com"),- ("unknown", "https://api.hyperspell.com"),+ ("us", HYPERSPELL_BASE_URLS["us"]),+ ("eu", HYPERSPELL_BASE_URLS["eu"]),+ ("EU", HYPERSPELL_BASE_URLS["eu"]),+ (" eu ", HYPERSPELL_BASE_URLS["eu"]),+ (None, HYPERSPELL_BASE_URLS["us"]),+ ("", HYPERSPELL_BASE_URLS["us"]),+ ("unknown", HYPERSPELL_BASE_URLS["us"]),],)- def test_base_url_by_region(self, region, expected):- assert _base_url(region) == expected+ def test_region_maps_to_base_url(self, region, expected) -> None:+ assert get_base_url(region) == expected++class TestParseUserIds:@pytest.mark.parametrize(- "params, expected",+ "raw, expected",[- ({"size": 100}, "https://api.hyperspell.com/memories/list?size=100"),- ({}, "https://api.hyperspell.com/memories/list"),+ (None, []),+ ("", []),+ (" , ", []),+ ("user-1", ["user-1"]),+ ("user-1, user-2", ["user-1", "user-2"]),+ ("user-1,user-1,user-2", ["user-1", "user-2"]),+ ("user-1\nuser-2", ["user-1", "user-2"]),],)- 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": []}+ def test_parses_and_dedupes(self, raw, expected) -> None:+ assert parse_user_ids(raw) == expectedclass TestValidateCredentials:@pytest.mark.parametrize(- "status_code, expected_ok",- [(200, True), (401, False), (403, False), (500, False)],+ "status, expected_valid",+ [+ (200, True),+ (401, False), # invalid key ("InvalidAPIKey")+ (403, False), # missing/unaccepted auth ("Not authenticated")+ (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+ def test_status_mapping(self, status, expected_valid) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(status)- @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"))+ is_valid, _ = validate_credentials("hs_test", "us")- batches = list(get_rows("key", "us", None, "memories", mock.MagicMock(), manager))+ assert is_valid is expected_valid- 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+ def test_network_error_is_invalid(self) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = Exception("boom")- @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()+ is_valid, message = validate_credentials("hs_test", "us")- assert list(get_rows("key", "us", None, "memories", mock.MagicMock(), manager)) == []- manager.save_state.assert_not_called()+ assert is_valid is False+ assert message is not None- @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())+ def test_probes_selected_region(self) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200)- 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+ validate_credentials("hs_test", "eu")++ called_url = mock_session.return_value.get.call_args[0][0]++ assert called_url.startswith(HYPERSPELL_BASE_URLS["eu"])+++class TestGetRows:+ def test_paginates_and_yields_each_page(self) -> None:+ manager = _StubManager()+ pages: list[dict[str, Any]] = [+ {"items": [{"resource_id": "r1", "source": "slack"}], "next_cursor": "c1"},+ {"items": [{"resource_id": "r2", "source": "slack"}], "next_cursor": None},+ ]++ batches, mock_get = _run(manager, pages)++ assert [[row["resource_id"] for row in batch] for batch in batches] == [["r1"], ["r2"]]+ second_url = mock_get.call_args_list[1][0][0]+ assert "cursor=c1" in second_url++ def test_saves_state_after_yielding_only_when_more_pages(self) -> None:+ manager = _StubManager()+ pages: list[dict[str, Any]] = [+ {"items": [{"resource_id": "r1", "source": "slack"}], "next_cursor": "c1"},+ {"items": [{"resource_id": "r2", "source": "slack"}], "next_cursor": None},+ ]++ _run(manager, pages)++ assert len(manager.saved) == 1+ assert manager.saved[0].cursor == "c1"++ def test_resumes_from_saved_cursor(self) -> None:+ manager = _StubManager(resume_state=HyperspellResumeConfig(cursor="resume_token", user_id=None))+ pages: list[dict[str, Any]] = [{"items": [{"resource_id": "r9", "source": "slack"}], "next_cursor": None}]++ _, mock_get = _run(manager, pages)++ assert "cursor=resume_token" in mock_get.call_args[0][0]++ def test_app_scope_stamps_empty_user_id_and_sends_no_header(self) -> None:+ manager = _StubManager()+ pages: list[dict[str, Any]] = [{"items": [{"resource_id": "r1", "source": "slack"}], "next_cursor": None}]++ batches, mock_get = _run(manager, pages)++ assert batches[0][0]["user_id"] == ""+ headers = mock_get.call_args[1]["headers"]+ assert "X-As-User" not in headers++ def test_fans_out_over_users_with_as_user_header(self) -> None:+ manager = _StubManager()+ pages: list[dict[str, Any]] = [+ {"items": [{"resource_id": "r1", "source": "slack"}], "next_cursor": None},+ {"items": [{"resource_id": "r1", "source": "slack"}], "next_cursor": None},+ ]++ batches, mock_get = _run(manager, pages, user_ids="user-1, user-2")++ assert [batch[0]["user_id"] for batch in batches] == ["user-1", "user-2"]+ headers_per_call = [call[1]["headers"].get("X-As-User") for call in mock_get.call_args_list]+ assert headers_per_call == ["user-1", "user-2"]+ # The bookmark advanced to user-2 after user-1 completed, so a crash between users+ # resumes into user-2 instead of re-fetching user-1.+ assert manager.saved[-1] == HyperspellResumeConfig(cursor=None, user_id="user-2")++ def test_resumes_into_bookmarked_user_and_skips_prior_users(self) -> None:+ manager = _StubManager(resume_state=HyperspellResumeConfig(cursor="c5", user_id="user-2"))+ pages: list[dict[str, Any]] = [{"items": [{"resource_id": "r1", "source": "slack"}], "next_cursor": None}]++ batches, mock_get = _run(manager, pages, user_ids="user-1, user-2")++ assert mock_get.call_count == 1+ assert mock_get.call_args[1]["headers"]["X-As-User"] == "user-2"+ assert "cursor=c5" in mock_get.call_args[0][0]+ assert batches[0][0]["user_id"] == "user-2"++ def test_bookmarked_user_removed_from_config_restarts_from_first_user(self) -> None:+ manager = _StubManager(resume_state=HyperspellResumeConfig(cursor="c5", user_id="user-gone"))+ pages: list[dict[str, Any]] = [+ {"items": [], "next_cursor": None},+ {"items": [], "next_cursor": None},+ ]++ _, mock_get = _run(manager, pages, user_ids="user-1, user-2")++ assert mock_get.call_count == 2+ first_url = mock_get.call_args_list[0][0][0]+ assert "cursor" not in first_url++ def test_non_paginated_endpoint_makes_single_request_without_page_params(self) -> None:+ manager = _StubManager()+ pages: list[dict[str, Any]] = [{"connections": [{"id": "conn-1", "integration_id": "int-1"}]}]++ batches, mock_get = _run(manager, pages, endpoint="connections")++ assert mock_get.call_count == 1+ assert "?" not in mock_get.call_args[0][0]+ assert batches[0][0]["id"] == "conn-1"+ assert manager.saved == []++ def test_app_level_endpoint_does_not_fan_out_or_stamp_user_id(self) -> None:+ manager = _StubManager()+ pages: list[dict[str, Any]] = [{"integrations": [{"id": "int-1"}]}]++ batches, mock_get = _run(manager, pages, endpoint="integrations", user_ids="user-1, user-2")++ assert mock_get.call_count == 1+ assert "X-As-User" not in mock_get.call_args[1]["headers"]+ assert "user_id" not in batches[0][0]++ def test_vaults_null_collection_becomes_empty_string(self) -> None:+ manager = _StubManager()+ pages: list[dict[str, Any]] = [{"items": [{"collection": None, "document_count": 3}], "next_cursor": None}]++ batches, _ = _run(manager, pages, endpoint="vaults")++ assert batches[0][0]["collection"] == ""++ def test_eu_region_hits_eu_base_url(self) -> None:+ manager = _StubManager()+ pages: list[dict[str, Any]] = [{"items": [], "next_cursor": None}]++ _, mock_get = _run(manager, pages, region="eu")++ assert mock_get.call_args[0][0].startswith(HYPERSPELL_BASE_URLS["eu"])@pytest.mark.parametrize(- "endpoint, expected_keys",+ "endpoint, page_size_param",[- ("memories", ["source", "resource_id"]),- ("connections", ["id"]),- ("queries", ["query_id"]),- ("context_documents", ["document_id"]),+ ("memories", "size=100"),+ ("entities", "limit=500"),],)- 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+ 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}]++ _, mock_get = _run(manager, pages, endpoint=endpoint)++ assert page_size_param in mock_get.call_args[0][0]++class TestHyperspellSource:@pytest.mark.parametrize(- "endpoint, expected_partition",+ "endpoint, expected_primary_keys",[- ("memories", "ingested_at"),- ("entities", "created_at"),- ("queries", "time"),- ("context_documents", "created_at"),- ("connections", None),- ("integrations", None),+ ("memories", ["user_id", "source", "resource_id"]),+ ("connections", ["user_id", "id"]),+ ("integrations", ["id"]),+ ("queries", ["query_id"]),],)- def test_partition_keys_are_stable_creation_timestamps(self, endpoint, expected_partition):- assert HYPERSPELL_ENDPOINTS[endpoint].partition_key == expected_partition+ def test_primary_keys_per_endpoint(self, endpoint, expected_primary_keys) -> None:+ response = hyperspell_source(+ api_key="hs_test",+ region="us",+ user_ids=None,+ endpoint=endpoint,+ logger=structlog.get_logger(),+ resumable_source_manager=mock.MagicMock(),+ )++ assert response.name == endpoint+ assert response.primary_keys == expected_primary_keys+ # Row ordering is undefined (opaque cursor, no sort param) so "asc" must never be declared.+ assert response.sort_mode == "desc"++ def test_entities_response_has_datetime_partition(self) -> None:+ response = hyperspell_source(+ api_key="hs_test",+ region="us",+ user_ids=None,+ endpoint="entities",+ logger=structlog.get_logger(),+ resumable_source_manager=mock.MagicMock(),+ )++ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]++ def test_memories_response_has_no_partition(self) -> None:+ response = hyperspell_source(+ api_key="hs_test",+ region="us",+ user_ids=None,+ endpoint="memories",+ logger=structlog.get_logger(),+ resumable_source_manager=mock.MagicMock(),+ )++ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --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.pyindex 9a4d060c1dbe..ae81ab7f5a7b 100644--- 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.py@@ -1,14 +1,11 @@import pytestfrom unittest import mock-from posthog.schema import (- DataWarehouseSourceCategory,- ReleaseStatus,- SourceFieldInputConfig,- SourceFieldInputConfigType,- SourceFieldSelectConfig,-)+import structlog++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HyperspellSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.hyperspell import (@@ -18,106 +15,113 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.hyperspellfrom products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.source import HyperspellSourcefrom products.warehouse_sources.backend.types import ExternalDataSourceType+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.hyperspell.source"+++def _make_inputs(schema_name: str = "memories") -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=123,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-id",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+class TestHyperspellSource:def setup_method(self):self.source = HyperspellSource()self.team_id = 123+ self.config = HyperspellSourceConfig(api_key="hs_test", region="eu", user_ids="user-1, user-2")def test_source_type(self):assert self.source.source_type == ExternalDataSourceType.HYPERSPELL- def test_source_config(self):+ def test_get_source_config(self):config = self.source.get_source_config++ assert config.name.value == "Hyperspell"assert config.label == "Hyperspell"- assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORINGassert 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"}+ assert config.iconPath == "/static/services/hyperspell.svg"+ assert [f.name for f in config.fields] == ["api_key", "region", "user_ids"]++ api_key_field = config.fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ region_field = config.fields[1]+ assert isinstance(region_field, SourceFieldSelectConfig)+ assert region_field.defaultValue == "us"+ assert [option.value for option in region_field.options] == ["us", "eu"]++ user_ids_field = config.fields[2]+ assert isinstance(user_ids_field, SourceFieldInputConfig)+ assert user_ids_field.required is False++ def test_get_schemas_lists_all_endpoints_as_full_refresh_only(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ # No Hyperspell endpoint has a server-side timestamp filter, so nothing may+ # advertise incremental support.+ 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=["memories", "nonexistent"])++ assert [schema.name for schema in schemas] == ["memories"]++ @pytest.mark.parametrize(+ "expected_key",+ [+ "401 Client Error: Unauthorized",+ "403 Client Error: Forbidden",+ ],+ )+ def test_non_retryable_errors_includes_auth_keys(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()- 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)+ @mock.patch(f"{MODULE}.validate_hyperspell_credentials")+ def test_validate_credentials_passes_region(self, mock_validate):+ mock_validate.return_value = (True, None)- @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()+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, "memories")- def test_canonical_descriptions_cover_every_endpoint(self):- descriptions = self.source.get_canonical_descriptions()- assert set(descriptions.keys()) == set(ENDPOINTS)+ assert is_valid is True+ assert error_message is None+ mock_validate.assert_called_once_with("hs_test", "eu", "memories")++ def test_get_resumable_source_manager(self):+ manager = self.source.get_resumable_source_manager(_make_inputs())- @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)+ @mock.patch(f"{MODULE}.hyperspell_source")+ def test_source_for_pipeline_plumbs_config(self, mock_hyperspell_source):manager = mock.MagicMock()- inputs = mock.MagicMock()- inputs.schema_name = "memories"- inputs.logger = mock.MagicMock()+ inputs = _make_inputs(schema_name="connections")- self.source.source_for_pipeline(config, manager, inputs)+ self.source.source_for_pipeline(self.config, manager, inputs)mock_hyperspell_source.assert_called_once_with(- api_key="key",- region="us",- user_id=None,- endpoint="memories",+ api_key="hs_test",+ region="eu",+ user_ids="user-1, user-2",+ endpoint="connections",logger=inputs.logger,resumable_source_manager=manager,)