: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 gainsight_px import source (#67831)
Tom Owers8888200a9167
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 35a2b3b348b4..29855ff52ece 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -156,6 +156,7 @@ the row lists both.| front | HTTP | requests | ✅ || fulcrum | HTTP | requests | ✅ || fullstory | HTTP | requests | ✅ |+| gainsight_px | HTTP | requests | ✅ || github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || giphy | HTTP | requests | ✅ || gitlab | HTTP | requests | ✅ |@@ -450,7 +451,6 @@ doesn't conflict with concurrent PRs.- freshchat- freshservice- fulcrum-- gainsight_px- gitbook- glassfrog- gmaildiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/canonical_descriptions.pynew file mode 100644index 000000000000..cee73c79eef2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/canonical_descriptions.py@@ -0,0 +1,136 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = (+ "https://support.gainsight.com/PX/API_for_Developers/02Usage_of_Different_APIs/Work_with_the_Gainsight_PX_REST_API"+)++# Descriptions curated from the Gainsight PX REST API docs. Date fields are returned by the API as+# epoch-millisecond integers and normalized to timestamps before loading.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "accounts": {+ "description": "Companies (accounts) tracked in Gainsight PX, aggregating the users that belong to them.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique account identifier.",+ "name": "Account (company) name.",+ "trackedSubscriptionId": "Subscription identifier the account is tracked under.",+ "sfdcId": "Salesforce account identifier, when linked.",+ "gsId": "Gainsight CS company identifier, when linked.",+ "industry": "Account industry.",+ "numberOfEmployees": "Reported number of employees.",+ "numberOfUsers": "Number of tracked users belonging to the account.",+ "plan": "Subscription plan the account is on.",+ "website": "Account website.",+ "healthScore": "Gainsight health score for the account.",+ "nps": "Latest NPS score for the account.",+ "csm": "Customer success manager assigned to the account.",+ "renewalDate": "Contract renewal date.",+ "parentGroupId": "Identifier used to group related accounts together.",+ "lastSeenDate": "Timestamp the account was last active.",+ "createDate": "Timestamp the account was created in Gainsight PX.",+ "lastModifiedDate": "Timestamp the account was last modified.",+ "customAttributes": "Map of custom attribute API name to value.",+ },+ },+ "users": {+ "description": "Individual end users tracked in Gainsight PX, with their profile and engagement attributes.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "User identifier (synonym for identifyId).",+ "identifyId": "Customer-supplied identifier used to identify the user.",+ "aptrinsicId": "Gainsight PX-generated user identifier.",+ "globalId": "Global user identifier (workspace-enabled subscriptions only).",+ "email": "User email address.",+ "firstName": "User first name.",+ "lastName": "User last name.",+ "title": "User job title.",+ "role": "User role.",+ "accountId": "Identifier of the account the user belongs to.",+ "subscriptionId": "Subscription the user is tracked under.",+ "score": "User engagement score.",+ "numberOfVisits": "Total number of sessions recorded for the user.",+ "sfdcContactId": "Salesforce contact identifier, when linked.",+ "globalUnsubscribe": "Whether the user has globally unsubscribed from engagements.",+ "signUpDate": "Timestamp the user signed up.",+ "firstVisitDate": "Timestamp of the user's first tracked visit.",+ "lastSeenDate": "Timestamp the user was last active.",+ "createDate": "Timestamp the user was created in Gainsight PX.",+ "lastModifiedDate": "Timestamp the user was last modified.",+ "customAttributes": "Map of custom attribute API name to value.",+ },+ },+ "features": {+ "description": "Product features tagged in Gainsight PX for adoption tracking.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique feature identifier.",+ "name": "Feature name.",+ "type": "Feature type.",+ "parentFeatureId": "Identifier of the parent feature, for nested features.",+ "propertyKey": "Aptrinsic tag key the feature belongs to.",+ "status": "Feature status.",+ "featureLabels": "Labels associated with the feature.",+ },+ },+ "segments": {+ "description": "User/account segments defined in Gainsight PX.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique segment identifier.",+ "name": "Segment name.",+ },+ },+ "engagements": {+ "description": "In-app engagements (guides, surveys, dialogs) configured in Gainsight PX.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique engagement identifier.",+ "name": "Engagement name.",+ "description": "Engagement description.",+ "type": "Engagement type (e.g. guide, survey, dialog).",+ "state": "Engagement lifecycle state.",+ "defaultLanguage": "Default language of the engagement.",+ "languages": "Languages the engagement is localized into.",+ "translationState": "Localization/translation state.",+ "envs": "Environments the engagement is published to.",+ },+ },+ "articles": {+ "description": "Knowledge Center articles published in Gainsight PX.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique article identifier.",+ "articleName": "Article title.",+ "author": "Article author.",+ "productId": "Identifier of the product the article belongs to.",+ "productName": "Name of the product the article belongs to.",+ "viewType": "Article view type.",+ "defaultLanguage": "Default language of the article.",+ "languages": "Languages the article is localized into.",+ "translationState": "Localization/translation state.",+ "releaseDate": "Article release date (ISO date string).",+ "createdDate": "Timestamp the article was created.",+ "modifiedDate": "Timestamp the article was last modified.",+ },+ },+ "kc_bots": {+ "description": "Knowledge Center bots configured in Gainsight PX.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique Knowledge Center bot identifier.",+ "name": "Bot name.",+ "description": "Bot description.",+ "status": "Bot status.",+ "priority": "Bot display priority.",+ "productId": "Identifier of the product the bot belongs to.",+ "productName": "Name of the product the bot belongs to.",+ "defaultLanguage": "Default language of the bot.",+ "languages": "Languages the bot is localized into.",+ "environments": "Environments the bot is published to.",+ "createdDate": "Timestamp the bot was created.",+ "modifiedDate": "Timestamp the bot was last modified.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/gainsight_px.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/gainsight_px.pynew file mode 100644index 000000000000..adfe49bd0e0f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/gainsight_px.py@@ -0,0 +1,230 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, datetime+from typing import Any+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 urllib3.util.retry import Retry++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.gainsight_px.settings import (+ EPOCH_MILLIS_FIELDS,+ GAINSIGHT_PX_ENDPOINTS,+ GAINSIGHT_PX_HOSTS,+)++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+# A defensive upper bound on pages fetched per endpoint. The loops terminate on the API's own+# last-page signals; this only guards against a mis-signalling API scrolling forever.+MAX_PAGES = 100_000+++class GainsightPxRetryableError(Exception):+ pass+++class GainsightPxResumeConfig:+ # Cursor token for scroll-paginated endpoints (users/accounts). None starts at the first page.+ scroll_id: str | None = None+ # Next page index for page-number-paginated endpoints (features/segments/…). None starts at 0.+ page_number: int | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {"X-APTRINSIC-API-KEY": api_key, "Accept": "application/json"}+++def _base_url(region: str) -> str:+ return GAINSIGHT_PX_HOSTS.get(region) or GAINSIGHT_PX_HOSTS["us"]+++def _build_url(base: str, params: dict[str, Any]) -> str:+ return f"{base}?{urlencode(params)}" if params else base+++def _normalize_row(item: dict[str, Any]) -> dict[str, Any]:+ """Convert the API's epoch-millisecond date fields to real datetimes.++ The warehouse then types these columns as timestamps (useful for querying) and the partitioner+ reads the datetime directly rather than misinterpreting raw millis as epoch seconds. `bool` is+ excluded because it's an `int` subclass and no boolean field is a date.+ """+ for name in EPOCH_MILLIS_FIELDS:+ value = item.get(name)+ if isinstance(value, int) and not isinstance(value, bool):+ item[name] = datetime.fromtimestamp(value / 1000, tz=UTC)+ return item+++@retry(+ retry=retry_if_exception_type(+ (+ GainsightPxRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ # 429 (rate limit) and 5xx are transient — retry. Everything else (401/403/400/404) is terminal;+ # `raise_for_status` surfaces it and `get_non_retryable_errors` maps auth failures to a message.+ if response.status_code == 429 or response.status_code >= 500:+ raise GainsightPxRetryableError(f"Gainsight PX API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Gainsight PX API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str, region: str) -> bool:+ url = _build_url(f"{_base_url(region)}/accounts", {"pageSize": 1})+ try:+ # `retry=Retry(total=0)` leaves retries to tenacity elsewhere; `redact_values` masks the API+ # key in captured samples since `X-APTRINSIC-API-KEY` isn't a name-redacted auth header.+ session = make_tracked_session(retry=Retry(total=0), redact_values=(api_key,))+ response = session.get(url, headers=_get_headers(api_key), timeout=REQUEST_TIMEOUT_SECONDS)+ return response.status_code == 200+ except (requests.ConnectionError, requests.Timeout):+ # Only transient network failures should read as "invalid credentials"; programming errors+ # (TypeError, AttributeError, …) must surface rather than being masked as a bad key.+ return False+++def _iter_scroll_pages(+ session: requests.Session,+ base: str,+ endpoint: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GainsightPxResumeConfig],+ resume: GainsightPxResumeConfig | None,+) -> Iterator[list[dict[str, Any]]]:+ """Page a scroll-paginated endpoint (users/accounts), yielding one page of rows at a time.++ Gainsight PX warns not to rely on `scrollId` becoming null, so the loop stops when a page returns+ fewer records than requested. State is saved AFTER yielding each page so a crash re-yields the+ last page (merge dedupes on the primary key) rather than skipping it.+ """+ config = GAINSIGHT_PX_ENDPOINTS[endpoint]+ scroll_id = resume.scroll_id if resume else None++ for _ in range(MAX_PAGES):+ params: dict[str, Any] = {"pageSize": config.page_size}+ if scroll_id:+ params["scrollId"] = scroll_id++ data = _fetch_page(session, _build_url(f"{base}{config.path}", params), headers, logger)+ records = data.get(config.data_key) or []+ if records:+ yield [_normalize_row(record) for record in records]++ next_scroll_id = data.get("scrollId")+ if len(records) < config.page_size or not next_scroll_id:+ return++ scroll_id = next_scroll_id+ resumable_source_manager.save_state(GainsightPxResumeConfig(scroll_id=scroll_id))+ else:+ logger.warning(f"Gainsight PX: hit MAX_PAGES page cap for endpoint={endpoint}")+++def _iter_numbered_pages(+ session: requests.Session,+ base: str,+ endpoint: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GainsightPxResumeConfig],+ resume: GainsightPxResumeConfig | None,+) -> Iterator[list[dict[str, Any]]]:+ """Page a page-number-paginated endpoint (features/segments/engagements/articles/kcbot).++ These responses carry an `isLastPage` flag; we also stop on a short page as a belt-and-braces+ guard. State (the next page index) is saved after each yielded page for the same reason as scroll.+ """+ config = GAINSIGHT_PX_ENDPOINTS[endpoint]+ page_number = resume.page_number if resume and resume.page_number is not None else 0++ for _ in range(MAX_PAGES):+ params = {"pageSize": config.page_size, "pageNumber": page_number}+ data = _fetch_page(session, _build_url(f"{base}{config.path}", params), headers, logger)+ records = data.get(config.data_key) or []+ if records:+ yield [_normalize_row(record) for record in records]++ if data.get("isLastPage") or len(records) < config.page_size:+ return++ page_number += 1+ resumable_source_manager.save_state(GainsightPxResumeConfig(page_number=page_number))+ else:+ logger.warning(f"Gainsight PX: hit MAX_PAGES page cap for endpoint={endpoint}")+++def get_rows(+ api_key: str,+ region: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GainsightPxResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = GAINSIGHT_PX_ENDPOINTS[endpoint]+ base = _base_url(region)+ headers = _get_headers(api_key)+ # One session reused across every page so urllib3 keeps the connection alive.+ # `retry=Retry(total=0)` leaves retries to tenacity in `_fetch_page` (rather than stacking urllib3+ # retries under them); `redact_values` masks the API key in captured samples since the custom+ # `X-APTRINSIC-API-KEY` header isn't one of the name-redacted auth headers.+ session = make_tracked_session(retry=Retry(total=0), redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if config.pagination == "scroll":+ yield from _iter_scroll_pages(session, base, endpoint, headers, logger, resumable_source_manager, resume)+ else:+ yield from _iter_numbered_pages(session, base, endpoint, headers, logger, resumable_source_manager, resume)+++def gainsight_px_source(+ api_key: str,+ region: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GainsightPxResumeConfig],+) -> SourceResponse:+ config = GAINSIGHT_PX_ENDPOINTS[endpoint]+ partition_key = config.partition_key++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ region=region,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if partition_key else None,+ partition_format="month" if partition_key else None,+ partition_keys=[partition_key] if partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/settings.pynew file mode 100644index 000000000000..bda54157183e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/settings.py@@ -0,0 +1,119 @@+from dataclasses import dataclass, field+from typing import Literal++from products.warehouse_sources.backend.types import IncrementalField++# Gainsight PX runs regional deployments. An API key belongs to a single subscription that lives in+# one region, so the host is picked by the `region` form field rather than a user-supplied URL — the+# set is fixed, so there is no SSRF surface.+GAINSIGHT_PX_HOSTS: dict[str, str] = {+ "us": "https://api.aptrinsic.com/v1",+ "eu": "https://api-eu.aptrinsic.com/v1",+ "us2": "https://api-us2.aptrinsic.com/v1",+}++# Scroll endpoints (users/accounts) cap `pageSize` at 1000; the page-number endpoints cap it lower+# (articles/kcbot allow up to 500). We keep the request size healthy but under each documented cap.+SCROLL_PAGE_SIZE = 1000+PAGE_NUMBER_PAGE_SIZE = 500++PaginationMode = Literal["scroll", "page"]++# Date fields come back as epoch-millisecond integers. We convert them to real datetimes before+# yielding so partition columns type as timestamps in the warehouse — the partitioner's integer+# branch assumes epoch *seconds*, so raw millis would produce nonsense partitions. `releaseDate`+# on articles is an ISO string, so it is deliberately excluded.+EPOCH_MILLIS_FIELDS: frozenset[str] = frozenset(+ {+ "createDate",+ "lastModifiedDate",+ "lastSeenDate",+ "signUpDate",+ "firstVisitDate",+ "renewalDate",+ "createdDate",+ "modifiedDate",+ }+)+++@dataclass+class GainsightPxEndpointConfig:+ name: str+ path: str+ # The list of records is wrapped under a named key that varies per endpoint (e.g. `users`,+ # `articleExternalViewList`); this is that key.+ data_key: str+ pagination: PaginationMode+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Must be a STABLE creation datetime (never `lastModifiedDate`/`lastSeenDate`) so partitions+ # don't rewrite every sync. `None` for resources the API returns without a creation timestamp.+ partition_key: str | None = None+ page_size: int = SCROLL_PAGE_SIZE+ # No Gainsight PX list endpoint exposes a server-side "updated since" filter, so every table is+ # full refresh — declared here for parity with other sources and future incremental work.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++# The entity endpoints Airbyte/Fivetran also expose. All are full refresh: the scroll endpoints+# (users/accounts) accept only `filter`/`sort`/`scrollId`, and the page-number endpoints accept only+# `pageNumber`/`pageSize` — none document an "updated since" server-side filter.+GAINSIGHT_PX_ENDPOINTS: dict[str, GainsightPxEndpointConfig] = {+ "accounts": GainsightPxEndpointConfig(+ name="accounts",+ path="/accounts",+ data_key="accounts",+ pagination="scroll",+ partition_key="createDate",+ ),+ "users": GainsightPxEndpointConfig(+ name="users",+ path="/users",+ data_key="users",+ pagination="scroll",+ partition_key="createDate",+ ),+ "features": GainsightPxEndpointConfig(+ name="features",+ path="/feature",+ data_key="features",+ pagination="page",+ page_size=PAGE_NUMBER_PAGE_SIZE,+ ),+ "segments": GainsightPxEndpointConfig(+ name="segments",+ path="/segment",+ data_key="segments",+ pagination="page",+ page_size=PAGE_NUMBER_PAGE_SIZE,+ ),+ "engagements": GainsightPxEndpointConfig(+ name="engagements",+ path="/engagement",+ data_key="engagements",+ pagination="page",+ page_size=PAGE_NUMBER_PAGE_SIZE,+ ),+ "articles": GainsightPxEndpointConfig(+ name="articles",+ path="/articles",+ data_key="articleExternalViewList",+ pagination="page",+ partition_key="createdDate",+ page_size=PAGE_NUMBER_PAGE_SIZE,+ ),+ "kc_bots": GainsightPxEndpointConfig(+ name="kc_bots",+ path="/kcbot",+ data_key="kcList",+ pagination="page",+ partition_key="createdDate",+ page_size=PAGE_NUMBER_PAGE_SIZE,+ ),+}++ENDPOINTS = tuple(GAINSIGHT_PX_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in GAINSIGHT_PX_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/source.pyindex 0fc1b3d083f4..1a2ce89cde76 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/source.py@@ -3,28 +3,155 @@ from typing import 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 SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_px.gainsight_px import (+ GainsightPxResumeConfig,+ gainsight_px_source,+ validate_credentials as validate_gainsight_px_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_px.settings import (+ ENDPOINTS,+ GAINSIGHT_PX_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GainsightPxSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class GainsightPxSource(SimpleSource[GainsightPxSourceConfig]):+class GainsightPxSource(ResumableSource[GainsightPxSourceConfig, GainsightPxResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GAINSIGHTPX+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ message = (+ "Gainsight PX rejected the API key. Generate a new key with Read access under "+ "Administration → REST API in Gainsight PX, then reconnect."+ )+ return {+ "401 Client Error: Unauthorized": message,+ "403 Client Error: Forbidden": message,+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_px.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: GainsightPxSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every Gainsight PX list endpoint is full refresh — none exposes a server-side "updated+ # since" filter, so there's no reliable incremental cursor.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ detected_primary_keys=GAINSIGHT_PX_ENDPOINTS[endpoint].primary_keys,+ )+ for endpoint in 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: GainsightPxSourceConfig, team_id: int, schema_name: str | None = None+ ) -> tuple[bool, str | None]:+ if validate_gainsight_px_credentials(config.api_key, config.region):+ return True, None++ return False, "Invalid Gainsight PX API key or region. Check the key and the region you selected."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GainsightPxResumeConfig]:+ return ResumableSourceManager[GainsightPxResumeConfig](inputs, GainsightPxResumeConfig)++ def source_for_pipeline(+ self,+ config: GainsightPxSourceConfig,+ resumable_source_manager: ResumableSourceManager[GainsightPxResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return gainsight_px_source(+ api_key=config.api_key,+ region=config.region,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.GAINSIGHT_PX,category=DataWarehouseSourceCategory.ANALYTICS,- label="Gainsight Px",+ label="Gainsight PX",+ caption=(+ "Connect Gainsight PX with your project's **API key**. Generate a key with **Read** "+ "access under **Administration → REST API** in Gainsight PX, then pick the region your "+ "subscription is hosted in.\n\n"+ "All tables are synced as full refresh — Gainsight PX's list endpoints don't expose an "+ '"updated since" filter.'+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/gainsight-px",iconPath="/static/services/gainsight_px.png",- fields=cast(list[FieldType], []),+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (api.aptrinsic.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (api-eu.aptrinsic.com)", value="eu"),+ SourceFieldSelectConfigOption(label="US2 (api-us2.aptrinsic.com)", value="us2"),+ ],+ ),+ ],+ ),unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/tests/test_gainsight_px.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/tests/test_gainsight_px.pynew file mode 100644index 000000000000..a49a41fee966--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/tests/test_gainsight_px.py@@ -0,0 +1,341 @@+from datetime import UTC, datetime+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_px import gainsight_px+from products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_px.gainsight_px import (+ GainsightPxResumeConfig,+ GainsightPxRetryableError,+ _base_url,+ _build_url,+ _normalize_row,+ gainsight_px_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_px.settings import (+ GAINSIGHT_PX_ENDPOINTS,+)+++class TestBaseUrl:+ @parameterized.expand(+ [+ ("us", "https://api.aptrinsic.com/v1"),+ ("eu", "https://api-eu.aptrinsic.com/v1"),+ ("us2", "https://api-us2.aptrinsic.com/v1"),+ ("unknown", "https://api.aptrinsic.com/v1"),+ ]+ )+ def test_base_url(self, region: str, expected: str) -> None:+ assert _base_url(region) == expected+++class TestBuildUrl:+ def test_encodes_params(self) -> None:+ url = _build_url("https://api.aptrinsic.com/v1/users", {"pageSize": 1000, "scrollId": "a b/c"})+ assert url == "https://api.aptrinsic.com/v1/users?pageSize=1000&scrollId=a+b%2Fc"++ def test_no_params(self) -> None:+ assert _build_url("https://api.aptrinsic.com/v1/users", {}) == "https://api.aptrinsic.com/v1/users"+++class TestNormalizeRow:+ def test_converts_epoch_millis_to_datetime(self) -> None:+ # 2021-01-01T00:00:00Z == 1609459200000 ms+ row = _normalize_row({"id": "u1", "createDate": 1609459200000})+ assert row["createDate"] == datetime(2021, 1, 1, tzinfo=UTC)++ def test_leaves_non_date_fields_untouched(self) -> None:+ row = _normalize_row({"id": "u1", "score": 42, "globalUnsubscribe": True, "name": "Acme"})+ assert row == {"id": "u1", "score": 42, "globalUnsubscribe": True, "name": "Acme"}++ def test_ignores_missing_and_non_int_dates(self) -> None:+ # releaseDate is an ISO string on articles — must not be reinterpreted as epoch millis.+ row = _normalize_row({"id": "a1", "releaseDate": "2021-01-01"})+ assert row["releaseDate"] == "2021-01-01"+++class TestFetchPage:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_status_codes_are_retried(self, _name: str, status_code: int) -> None:+ retryable = MagicMock(status_code=status_code)+ good = MagicMock(status_code=200, ok=True)+ good.json.return_value = {"users": []}++ session = MagicMock()+ session.get.side_effect = [retryable, good]++ with patch.object(gainsight_px._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = gainsight_px._fetch_page(session, "https://api.aptrinsic.com/v1/users", {}, MagicMock())++ assert result == {"users": []}+ assert session.get.call_count == 2++ @parameterized.expand(+ [+ ("read_timeout", requests.ReadTimeout("timed out")),+ ("connection_error", requests.ConnectionError("reset")),+ ]+ )+ def test_transient_network_errors_are_retried(self, _name: str, error: Exception) -> None:+ good = MagicMock(status_code=200, ok=True)+ good.json.return_value = {"users": []}+ session = MagicMock()+ session.get.side_effect = [error, good]++ with patch.object(gainsight_px._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = gainsight_px._fetch_page(session, "https://api.aptrinsic.com/v1/users", {}, MagicMock())++ assert result == {"users": []}+ assert session.get.call_count == 2++ def test_auth_error_is_not_retried(self) -> None:+ response = MagicMock(status_code=401, ok=False, text="unauthorized")+ response.raise_for_status.side_effect = requests.HTTPError(+ "401 Client Error: Unauthorized", response=cast(requests.Response, response)+ )+ session = MagicMock()+ session.get.return_value = response++ with patch.object(gainsight_px._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(requests.HTTPError):+ gainsight_px._fetch_page(session, "https://api.aptrinsic.com/v1/users", {}, MagicMock())++ assert session.get.call_count == 1++ def test_retry_exhausts_and_reraises(self) -> None:+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=500)++ with patch.object(gainsight_px._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(GainsightPxRetryableError):+ gainsight_px._fetch_page(session, "https://api.aptrinsic.com/v1/users", {}, MagicMock())++ assert session.get.call_count == 5+++class _FakeResumableManager:+ def __init__(self, state: GainsightPxResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[GainsightPxResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> GainsightPxResumeConfig | None:+ return self._state++ def save_state(self, data: GainsightPxResumeConfig) -> None:+ self.saved.append(data)+++def _collect(endpoint: str, manager: _FakeResumableManager, monkeypatch: Any, responses: list[dict]) -> list[dict]:+ """Run get_rows with a canned sequence of API responses and flatten the yielded pages."""+ it = iter(responses)++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ return next(it)++ monkeypatch.setattr(gainsight_px, "_fetch_page", fake_fetch)+ monkeypatch.setattr(gainsight_px, "make_tracked_session", lambda *a, **k: MagicMock())++ rows: list[dict] = []+ for page in get_rows(+ api_key="key",+ region="us",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(page)+ return rows+++class TestScrollPagination:+ def test_follows_scroll_id_and_stops_on_short_page(self, monkeypatch: Any) -> None:+ # users caps at a large pageSize; shrink it so a 2-then-1 record run terminates.+ monkeypatch.setattr(GAINSIGHT_PX_ENDPOINTS["users"], "page_size", 2)+ manager = _FakeResumableManager()++ rows = _collect(+ "users",+ manager,+ monkeypatch,+ [+ {"users": [{"id": "1"}, {"id": "2"}], "scrollId": "s1"},+ {"users": [{"id": "3"}], "scrollId": "s2"}, # short page → stop+ ],+ )++ assert [r["id"] for r in rows] == ["1", "2", "3"]+ # State saved after the first (full) page only, carrying the next scroll cursor.+ assert [s.scroll_id for s in manager.saved] == ["s1"]++ def test_stops_when_scroll_id_absent(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(GAINSIGHT_PX_ENDPOINTS["accounts"], "page_size", 2)+ manager = _FakeResumableManager()++ rows = _collect(+ "accounts",+ manager,+ monkeypatch,+ [{"accounts": [{"id": "1"}, {"id": "2"}], "scrollId": None}],+ )++ assert [r["id"] for r in rows] == ["1", "2"]+ assert manager.saved == []++ def test_resumes_from_saved_scroll_id(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(GAINSIGHT_PX_ENDPOINTS["users"], "page_size", 2)+ seen_urls: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ seen_urls.append(url)+ return {"users": [{"id": "9"}], "scrollId": None}++ monkeypatch.setattr(gainsight_px, "_fetch_page", fake_fetch)+ monkeypatch.setattr(gainsight_px, "make_tracked_session", lambda *a, **k: MagicMock())++ manager = _FakeResumableManager(GainsightPxResumeConfig(scroll_id="saved-cursor"))+ list(+ get_rows(+ api_key="key",+ region="us",+ endpoint="users",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ )+ )++ assert "scrollId=saved-cursor" in seen_urls[0]+++class TestPageNumberPagination:+ def test_stops_on_is_last_page(self, monkeypatch: Any) -> None:+ # page_size 1 keeps each page "full", so isLastPage (not the short-page guard) is what stops us.+ monkeypatch.setattr(GAINSIGHT_PX_ENDPOINTS["features"], "page_size", 1)+ manager = _FakeResumableManager()++ rows = _collect(+ "features",+ manager,+ monkeypatch,+ [+ {"features": [{"id": "f1"}], "isLastPage": False},+ {"features": [{"id": "f2"}], "isLastPage": True},+ ],+ )++ assert [r["id"] for r in rows] == ["f1", "f2"]+ assert [s.page_number for s in manager.saved] == [1]++ def test_stops_on_short_page(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(GAINSIGHT_PX_ENDPOINTS["segments"], "page_size", 2)+ manager = _FakeResumableManager()++ rows = _collect(+ "segments",+ manager,+ monkeypatch,+ [{"segments": [{"id": "s1"}], "isLastPage": False}], # short page → stop even without isLastPage+ )++ assert [r["id"] for r in rows] == ["s1"]+ assert manager.saved == []++ def test_resumes_from_saved_page_number(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(GAINSIGHT_PX_ENDPOINTS["features"], "page_size", 100)+ seen_urls: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ seen_urls.append(url)+ return {"features": [{"id": "f"}], "isLastPage": True}++ monkeypatch.setattr(gainsight_px, "_fetch_page", fake_fetch)+ monkeypatch.setattr(gainsight_px, "make_tracked_session", lambda *a, **k: MagicMock())++ manager = _FakeResumableManager(GainsightPxResumeConfig(page_number=4))+ list(+ get_rows(+ api_key="key",+ region="us",+ endpoint="features",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ )+ )++ assert "pageNumber=4" in seen_urls[0]+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_maps_status_to_bool(self, _name: str, status_code: int, expected: bool) -> None:+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=status_code)+ with patch.object(gainsight_px, "make_tracked_session", return_value=session):+ assert validate_credentials("key", "us") is expected++ def test_network_error_is_false(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(gainsight_px, "make_tracked_session", return_value=session):+ assert validate_credentials("key", "us") is False+++class TestSessionHardening:+ """The API key travels in a custom `X-APTRINSIC-API-KEY` header, which the sample-capture+ denylist can't recognise. Every session must value-mask the key and leave retries to tenacity."""++ @staticmethod+ def _assert_hardened(call: Any) -> None:+ assert call.kwargs["redact_values"] == ("secret-key",)+ assert call.kwargs["retry"].total == 0++ def test_validate_credentials_masks_key_and_disables_adapter_retry(self) -> None:+ with patch.object(gainsight_px, "make_tracked_session", return_value=MagicMock()) as make_session:+ validate_credentials("secret-key", "us")+ self._assert_hardened(make_session.call_args)++ def test_get_rows_masks_key_and_disables_adapter_retry(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(gainsight_px, "_fetch_page", lambda *a, **k: {"users": [], "scrollId": None})+ with patch.object(gainsight_px, "make_tracked_session", return_value=MagicMock()) as make_session:+ list(get_rows("secret-key", "us", "users", MagicMock(), MagicMock()))+ self._assert_hardened(make_session.call_args)+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("accounts", ["id"], "createDate"),+ ("users", ["id"], "createDate"),+ ("features", ["id"], None),+ ("segments", ["id"], None),+ ("engagements", ["id"], None),+ ("articles", ["id"], "createdDate"),+ ("kc_bots", ["id"], "createdDate"),+ ]+ )+ def test_source_response_shape(self, endpoint: str, primary_keys: list[str], partition_key: str | None) -> None:+ response = gainsight_px_source(+ api_key="key",+ region="us",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )++ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ if partition_key is None:+ assert response.partition_mode is None+ assert response.partition_keys is None+ else:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/tests/test_gainsight_px_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/tests/test_gainsight_px_source.pynew file mode 100644index 000000000000..aeadd6ff69e9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gainsight_px/tests/test_gainsight_px_source.py@@ -0,0 +1,134 @@+from types import SimpleNamespace+from typing import cast++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_px.gainsight_px import (+ GainsightPxResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_px.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_px.source import GainsightPxSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GainsightPxSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestGainsightPxSource:+ def setup_method(self):+ self.source = GainsightPxSource()+ self.team_id = 123+ self.config = GainsightPxSourceConfig(api_key="key", region="us")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.GAINSIGHTPX++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "GainsightPx"+ assert config.label == "Gainsight PX"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/gainsight_px.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/gainsight-px"+ assert len(config.fields) == 2++ api_key_field = config.fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ 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.name == "region"+ assert region_field.defaultValue == "us"+ assert {option.value for option in region_field.options} == {"us", "eu", "us2"}++ @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_get_schemas_returns_every_endpoint(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_every_endpoint_is_full_refresh(self, endpoint):+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ # No Gainsight PX list endpoint exposes a server-side "updated since" filter, so every+ # table must be full refresh — advertising incremental would silently corrupt the cursor.+ assert schema.supports_incremental is False+ assert schema.supports_append is False++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_every_endpoint_advertises_a_primary_key(self, endpoint):+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert schema.detected_primary_keys++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["users"])+ assert len(schemas) == 1+ assert schemas[0].name == "users"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ def test_lists_tables_without_credentials(self):+ # A static endpoint catalog with no I/O, so the public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ # Canonical descriptions should flow into the documented catalog.+ users = next(t for t in tables if t["name"] == "users")+ assert users["description"]+ assert users["sync_methods"] == ["Full refresh"]++ @pytest.mark.parametrize(+ "mock_return, expected_valid",+ [(True, True), (False, False)],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_px.source.validate_gainsight_px_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert (error_message is None) is expected_valid+ mock_validate.assert_called_once_with(self.config.api_key, self.config.region)++ def test_get_resumable_source_manager_is_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is GainsightPxResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_px.source.gainsight_px_source"+ )+ def test_source_for_pipeline_plumbs_inputs(self, mock_gainsight_source):+ mock_gainsight_source.return_value = SimpleNamespace(name="users")+ manager = mock.MagicMock(spec=ResumableSourceManager)+ logger = mock.MagicMock()+ inputs = SimpleNamespace(schema_name="users", team_id=self.team_id, job_id="job-1", logger=logger)++ response = self.source.source_for_pipeline(self.config, manager, cast(SourceInputs, inputs))++ mock_gainsight_source.assert_called_once_with(+ api_key="key",+ region="us",+ endpoint="users",+ logger=logger,+ resumable_source_manager=manager,+ )+ assert response is mock_gainsight_source.return_valuediff --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 82d289a906ae..582679a6b52e 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@@ -1306,7 +1306,8 @@ class GNewsSourceConfig(config.Config):@config.configclass GainsightPxSourceConfig(config.Config):- pass+ api_key: str+ region: Literal["us", "eu", "us2"] = config.value(default="us")@config.config