Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add gainsight px event stream tables (#109106)

Tom Owers166afa7052ba
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index c7c82dc2268f..802ec897d286 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -3505,10 +3505,10 @@ Today (7): `accounts`, `articles`, `engagements`, `features`, `kc_bots`, `segmen
Diffed against: <https://jsapi.apiary.io/apis/gainsightpx.apib>
-- [ ] `events/feature_match` — feature usage events — the headline Gainsight PX metric, and the join from the features table we already sync to actual usage (high)
-- [ ] `events/pageView` — the core page-view event stream underpinning any adoption or navigation analysis (high)
-- [ ] `events/session` — session-level events giving visit frequency, duration and stickiness (high)
-- [ ] `events/engagementView` — who saw and interacted with each engagement — the only way to measure the engagements table's performance (high)
+- [x] `events/feature_match` — feature usage events — the headline Gainsight PX metric, and the join from the features table we already sync to actual usage (high)
+- [x] `events/pageView` — the core page-view event stream underpinning any adoption or navigation analysis (high)
+- [x] `events/session` — session-level events giving visit frequency, duration and stickiness (high)
+- [x] `events/engagementView` — who saw and interacted with each engagement — the only way to measure the engagements table's performance (high)
- [ ] `survey/responses` — NPS/CES/survey answers, a headline reporting object with no substitute (high)
- [ ] `events/custom` — customer-defined events captured by PX, typically the business-critical ones (high)
- [ ] `events/segment_match` — segment entry/exit events that resolve the segments table into per-user membership over time (medium)
diff --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.py
index cee73c79eef2..3f51998dac73 100644
--- 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.py
@@ -5,6 +5,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
_DOCS_URL = (
"https://support.gainsight.com/PX/API_for_Developers/02Usage_of_Different_APIs/Work_with_the_Gainsight_PX_REST_API"
)
+_EVENTS_DOCS_URL = "https://px-apidocs.gainsight.com/"
+
+_EVENT_COLUMNS: dict[str, str] = {
+ "eventId": "Unique event identifier.",
+ "identifyId": "Identifier of the user who triggered the event.",
+ "accountId": "Identifier of the account the user belongs to.",
+ "propertyKey": "Aptrinsic tag key of the product the event was captured in.",
+ "date": "Timestamp the event occurred.",
+ "eventType": "Type of the event.",
+ "sessionId": "Identifier of the session the event belongs to.",
+ "userType": "Type of the user who triggered the event (e.g. user or lead).",
+ "globalContext": "Global context attributes set on the page when the event was captured.",
+}
# 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.
@@ -133,4 +146,67 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"modifiedDate": "Timestamp the bot was last modified.",
},
},
+ "page_view_events": {
+ "description": "Page view events captured by the Gainsight PX tag, one row per page viewed.",
+ "docs_url": _EVENTS_DOCS_URL,
+ "columns": {
+ **_EVENT_COLUMNS,
+ "scheme": "URL scheme of the viewed page.",
+ "host": "Host of the viewed page.",
+ "path": "Path of the viewed page.",
+ "queryString": "Query string of the viewed page.",
+ "hash": "URL fragment of the viewed page.",
+ "queryParams": "Parsed query string parameters of the viewed page.",
+ "remoteHost": "IP address the request came from.",
+ "referrer": "Referring URL.",
+ "screenHeight": "Screen height in pixels.",
+ "screenWidth": "Screen width in pixels.",
+ "languages": "Browser languages.",
+ "pageTitle": "Title of the viewed page.",
+ },
+ },
+ "session_events": {
+ "description": "Session initialized events, one row per user session started.",
+ "docs_url": _EVENTS_DOCS_URL,
+ "columns": {
+ **_EVENT_COLUMNS,
+ "remoteHost": "IP address the session started from.",
+ "inferredLocation": "Location inferred from the IP address.",
+ },
+ },
+ "engagement_view_events": {
+ "description": "Engagement view events: views of and interactions with in-app engagements (guides, surveys, dialogs).",
+ "docs_url": _EVENTS_DOCS_URL,
+ "columns": {
+ **_EVENT_COLUMNS,
+ "engagementId": "Identifier of the engagement. Joins to the engagements table.",
+ "engagementTrackType": "Tracking type of the engagement.",
+ "contentId": "Identifier of the engagement content.",
+ "contentType": "Type of the engagement content (e.g. guide, survey, carousel).",
+ "executionDate": "Timestamp of the engagement view. The same on all events of one view.",
+ "executionId": "Identifier of the engagement view. The same on all events of one view.",
+ "viewEventId": "Identifier of the view event.",
+ "carouselState": "State of a carousel engagement.",
+ "slideId": "Identifier of the carousel slide.",
+ "sequenceNumber": "Sequence number of the event within the engagement view.",
+ "linkUrl": "URL of a clicked link.",
+ "guideState": "State of a guide engagement.",
+ "stepId": "Identifier of the guide step.",
+ "surveyState": "State of a survey engagement.",
+ "contactMeAllowed": "Whether the user allowed follow-up contact from a survey.",
+ "score": "Survey score the user gave.",
+ "comment": "Survey comment the user wrote.",
+ "questionType": "Type of the survey question.",
+ "selectionIds": "Identifiers of the options the user selected.",
+ "path": "Path of the page the engagement was viewed on.",
+ },
+ },
+ "feature_match_events": {
+ "description": "Feature match events, one row each time a user uses a tagged feature.",
+ "docs_url": _EVENTS_DOCS_URL,
+ "columns": {
+ **_EVENT_COLUMNS,
+ "featureId": "Identifier of the matched feature. Joins to the features table.",
+ },
+ },
}
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.py
index b11be21eec99..8e1e9397a284 100644
--- 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.py
@@ -1,10 +1,13 @@
import dataclasses
-from datetime import UTC, datetime
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
from typing import Any, Optional
from urllib.parse import urlencode
from requests import Request, Response
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
@@ -16,6 +19,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sou
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_px.settings import (
EPOCH_MILLIS_FIELDS,
+ EVENT_BACKFILL_DAYS,
+ EVENT_DATE_FIELD,
+ EVENT_WINDOW_DAYS,
GAINSIGHT_PX_ENDPOINTS,
GAINSIGHT_PX_HOSTS,
)
@@ -24,13 +30,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_
# (api_key/header) means its value is scrubbed from every raised error and captured sample.
API_KEY_HEADER = "X-APTRINSIC-API-KEY"
+MILLIS_PER_DAY = 24 * 60 * 60 * 1000
+
[email protected](frozen=False)
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
+ # Start (epoch millis) of the date window an event stream is walking. `scroll_id` belongs to it.
+ window_start: int | None = None
def _base_url(region: str) -> str:
@@ -55,6 +65,33 @@ def _normalize_row(item: dict[str, Any]) -> dict[str, Any]:
return item
+def _to_epoch_millis(value: Any) -> int:
+ # The watermark is read back from the warehouse, where `date` is stored as the datetime
+ # `_normalize_row` produced; the API filters on epoch millis.
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return int(dt.timestamp() * 1000)
+ if isinstance(value, date):
+ return int(datetime(value.year, value.month, value.day, tzinfo=UTC).timestamp() * 1000)
+ if isinstance(value, int | float):
+ return int(value)
+ return _to_epoch_millis(datetime.fromisoformat(str(value)))
+
+
+@frozen
+class _EventWindow:
+ start: int
+ end: int
+
+
+def _event_windows(start_ms: int, end_ms: int) -> Iterator[_EventWindow]:
+ window_ms = EVENT_WINDOW_DAYS * MILLIS_PER_DAY
+ while start_ms < end_ms:
+ window_end = min(start_ms + window_ms, end_ms)
+ yield _EventWindow(start=start_ms, end=window_end)
+ start_ms = window_end
+
+
class _ScrollPaginator(BasePaginator):
"""Scroll (cursor) pagination for users/accounts.
@@ -152,24 +189,11 @@ class _PageNumberPaginator(BasePaginator):
self._has_next_page = True
-def gainsight_px_source(
- api_key: str,
- region: str,
- endpoint: str,
- team_id: int,
- job_id: str,
- resumable_source_manager: ResumableSourceManager[GainsightPxResumeConfig],
-) -> SourceResponse:
+def _rest_config(
+ api_key: str, region: str, endpoint: str, params: dict[str, Any], paginator: BasePaginator
+) -> RESTAPIConfig:
config = GAINSIGHT_PX_ENDPOINTS[endpoint]
- partition_key = config.partition_key
-
- paginator: BasePaginator
- if config.pagination == "scroll":
- paginator = _ScrollPaginator(page_size=config.page_size)
- else:
- paginator = _PageNumberPaginator(page_size=config.page_size)
-
- rest_config: RESTAPIConfig = {
+ return {
"client": {
"base_url": _base_url(region),
# Only the non-secret Accept header goes here; the API key rides on framework `auth` so
@@ -183,7 +207,7 @@ def gainsight_px_source(
"name": endpoint,
"endpoint": {
"path": config.path,
- "params": {"pageSize": config.page_size},
+ "params": params,
"data_selector": config.data_key,
},
"data_map": _normalize_row,
@@ -191,6 +215,98 @@ def gainsight_px_source(
],
}
+
+def _event_pages(
+ api_key: str,
+ region: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[GainsightPxResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+) -> Iterator[Any]:
+ config = GAINSIGHT_PX_ENDPOINTS[endpoint]
+ end_ms = int(datetime.now(tz=UTC).timestamp() * 1000)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ scroll_id: Optional[str] = None
+ if resume is not None and resume.window_start is not None:
+ start_ms = resume.window_start
+ scroll_id = resume.scroll_id
+ elif db_incremental_field_last_value is not None:
+ start_ms = _to_epoch_millis(db_incremental_field_last_value)
+ else:
+ start_ms = end_ms - EVENT_BACKFILL_DAYS * MILLIS_PER_DAY
+
+ for window in _event_windows(start_ms, end_ms):
+ params = {
+ "pageSize": config.page_size,
+ # Ascending within ascending windows lets the pipeline checkpoint the watermark per batch.
+ "sort": EVENT_DATE_FIELD,
+ "filter": f"{EVENT_DATE_FIELD}>={window.start};{EVENT_DATE_FIELD}<{window.end}",
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]], _window_start: int = window.start) -> None:
+ if state and state.get("scroll_id") is not None:
+ resumable_source_manager.save_state(
+ GainsightPxResumeConfig(scroll_id=str(state["scroll_id"]), window_start=_window_start)
+ )
+
+ yield from rest_api_resource(
+ _rest_config(api_key, region, endpoint, params, _ScrollPaginator(page_size=config.page_size)),
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state={"scroll_id": scroll_id} if scroll_id is not None else None,
+ )
+ scroll_id = None
+ if window.end < end_ms:
+ resumable_source_manager.save_state(GainsightPxResumeConfig(window_start=window.end))
+
+
+def gainsight_px_source(
+ api_key: str,
+ region: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[GainsightPxResumeConfig],
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = GAINSIGHT_PX_ENDPOINTS[endpoint]
+ partition_key = config.partition_key
+ response_kwargs: dict[str, Any] = {
+ "name": endpoint,
+ "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,
+ "sort_mode": "asc",
+ }
+
+ if config.incremental_fields:
+ return SourceResponse(
+ items=lambda: _event_pages(
+ api_key,
+ region,
+ endpoint,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ db_incremental_field_last_value,
+ ),
+ **response_kwargs,
+ )
+
+ paginator: BasePaginator
+ if config.pagination == "scroll":
+ paginator = _ScrollPaginator(page_size=config.page_size)
+ else:
+ paginator = _PageNumberPaginator(page_size=config.page_size)
+
initial_paginator_state: Optional[dict[str, Any]] = None
if resumable_source_manager.can_resume():
resume = resumable_source_manager.load_state()
@@ -211,25 +327,15 @@ def gainsight_px_source(
resumable_source_manager.save_state(GainsightPxResumeConfig(page_number=int(state["page_number"])))
resource = rest_api_resource(
- rest_config,
+ _rest_config(api_key, region, endpoint, {"pageSize": config.page_size}, paginator),
team_id,
job_id,
- None, # every Gainsight PX endpoint is full refresh
+ None, # every entity endpoint is full refresh
resume_hook=save_checkpoint,
initial_paginator_state=initial_paginator_state,
)
- return SourceResponse(
- name=endpoint,
- items=lambda: resource,
- 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,
- column_hints=resource.column_hints,
- )
+ return SourceResponse(items=lambda: resource, column_hints=resource.column_hints, **response_kwargs)
def validate_credentials(api_key: str, region: str) -> bool:
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.py
index 4a55d405e3d4..83f1101621b2 100644
--- 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.py
@@ -1,7 +1,7 @@
from dataclasses import dataclass, field
from typing import Literal
-from products.warehouse_sources.backend.types import IncrementalField
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
# 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
@@ -14,7 +14,8 @@ GAINSIGHT_PX_HOSTS: dict[str, str] = {
# The `pageSize` cap differs per endpoint and a request above an endpoint's cap is rejected with a
# 400, so every endpoint carries its own size. Scroll endpoints (users/accounts) allow up to 1000,
-# engagement/articles/kcbot allow up to 500, and feature/segment allow only 200.
+# engagement/articles/kcbot allow up to 500, and feature/segment allow only 200. The `/events/*`
+# streams are scroll-paginated and share the 1000 cap.
SCROLL_PAGE_SIZE = 1000
PAGE_NUMBER_PAGE_SIZE = 500
FEATURE_SEGMENT_PAGE_SIZE = 200
@@ -35,11 +36,31 @@ EPOCH_MILLIS_FIELDS: frozenset[str] = frozenset(
"renewalDate",
"createdDate",
"modifiedDate",
+ "date",
+ "executionDate",
}
)
+# The `/events/*` streams accept `filter=date>=<epoch millis>` and `sort=date`, which is what makes
+# them incremental. Events are immutable, so `date` never changes after capture.
+EVENT_DATE_FIELD = "date"
+# An events request without a date range returns only the last day, and a range above 190 days is a
+# 400, so event syncs walk explicit windows. 180 days leaves headroom under the cap.
+EVENT_WINDOW_DAYS = 180
+# How far back the first sync (and every full refresh) of an event table reaches. The API documents
+# no retention limit, so this bounds the backfill.
+EVENT_BACKFILL_DAYS = 730
+EVENT_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": EVENT_DATE_FIELD,
+ "type": IncrementalFieldType.DateTime,
+ "field": EVENT_DATE_FIELD,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+]
+
-@dataclass
+@dataclass(frozen=False)
class GainsightPxEndpointConfig:
name: str
path: str
@@ -52,12 +73,12 @@ class GainsightPxEndpointConfig:
# 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.
+ # Only the `/events/*` streams expose a server-side date filter; the entity endpoints have no
+ # "updated since" filter and stay full refresh.
incremental_fields: list[IncrementalField] = field(default_factory=list)
-# The entity endpoints Airbyte/Fivetran also expose. All are full refresh: the scroll endpoints
+# The entity endpoints 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] = {
@@ -112,6 +133,42 @@ GAINSIGHT_PX_ENDPOINTS: dict[str, GainsightPxEndpointConfig] = {
partition_key="createdDate",
page_size=PAGE_NUMBER_PAGE_SIZE,
),
+ "page_view_events": GainsightPxEndpointConfig(
+ name="page_view_events",
+ path="/events/pageView",
+ data_key="results",
+ pagination="scroll",
+ primary_keys=["eventId"],
+ partition_key=EVENT_DATE_FIELD,
+ incremental_fields=EVENT_INCREMENTAL_FIELDS,
+ ),
+ "session_events": GainsightPxEndpointConfig(
+ name="session_events",
+ path="/events/session",
+ data_key="sessionInitializedEvents",
+ pagination="scroll",
+ primary_keys=["eventId"],
+ partition_key=EVENT_DATE_FIELD,
+ incremental_fields=EVENT_INCREMENTAL_FIELDS,
+ ),
+ "engagement_view_events": GainsightPxEndpointConfig(
+ name="engagement_view_events",
+ path="/events/engagementView",
+ data_key="results",
+ pagination="scroll",
+ primary_keys=["eventId"],
+ partition_key=EVENT_DATE_FIELD,
+ incremental_fields=EVENT_INCREMENTAL_FIELDS,
+ ),
+ "feature_match_events": GainsightPxEndpointConfig(
+ name="feature_match_events",
+ path="/events/feature_match",
+ data_key="featureMatchEvents",
+ pagination="scroll",
+ primary_keys=["eventId"],
+ partition_key=EVENT_DATE_FIELD,
+ incremental_fields=EVENT_INCREMENTAL_FIELDS,
+ ),
}
ENDPOINTS = tuple(GAINSIGHT_PX_ENDPOINTS.keys())
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.py
index a26c58bfc921..be3e32c39697 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
@@ -68,13 +68,13 @@ class GainsightPxSource(ResumableSource[GainsightPxSourceConfig, GainsightPxResu
force_refresh: bool = False,
api_version: str | None = None,
) -> 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.
+ # Only the `/events/*` streams expose a server-side date filter; the entity endpoints have
+ # no "updated since" filter and stay full refresh.
schemas = [
SourceSchema(
name=endpoint,
- supports_incremental=False,
- supports_append=False,
+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
detected_primary_keys=GAINSIGHT_PX_ENDPOINTS[endpoint].primary_keys,
)
@@ -115,6 +115,9 @@ class GainsightPxSource(ResumableSource[GainsightPxSourceConfig, GainsightPxResu
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
@property
@@ -127,8 +130,9 @@ class GainsightPxSource(ResumableSource[GainsightPxSourceConfig, GainsightPxResu
"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.'
+ "Event tables (page views, sessions, engagement views and feature matches) can sync "
+ "incrementally on the event `date`. The other tables sync as full refresh because "
+ 'Gainsight PX doesn\'t expose an "updated since" filter for them.'
),
docsUrl="https://posthog.com/docs/cdp/sources/gainsight-px",
iconPath="/static/services/gainsight_px.png",
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.py
index efae0d6d76ed..ab4b9aa78ec9 100644
--- 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.py
@@ -1,7 +1,10 @@
import json
-from datetime import UTC, datetime
+from collections.abc import Iterator
+from datetime import UTC, datetime, timedelta
from typing import Any
+import pytest
+import time_machine
from unittest import mock
from parameterized import parameterized
@@ -12,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.gainsight_
_base_url,
_build_url,
_normalize_row,
+ _to_epoch_millis,
gainsight_px_source,
validate_credentials,
)
@@ -63,7 +67,7 @@ def _rows(source_response: Any) -> list[dict[str, Any]]:
return [row for page in source_response.items() for row in page]
-def _source(endpoint: str, manager: mock.MagicMock) -> Any:
+def _source(endpoint: str, manager: mock.MagicMock, db_incremental_field_last_value: Any = None) -> Any:
return gainsight_px_source(
api_key="secret-key",
region="us",
@@ -71,6 +75,7 @@ def _source(endpoint: str, manager: mock.MagicMock) -> Any:
team_id=1,
job_id="j",
resumable_source_manager=manager,
+ db_incremental_field_last_value=db_incremental_field_last_value,
)
@@ -236,6 +241,10 @@ VENDOR_PAGE_SIZE_MAXIMA: dict[str, int] = {
"kc_bots": 500,
"segments": 200,
"users": 1000,
+ "page_view_events": 1000,
+ "session_events": 1000,
+ "engagement_view_events": 1000,
+ "feature_match_events": 1000,
}
@@ -247,7 +256,7 @@ class TestPageSizeCaps:
data_key = GAINSIGHT_PX_ENDPOINTS[endpoint].data_key
params = _wire(session, [_response(data_key, [{"id": "1"}], isLastPage=True, scrollId=None)])
- _rows(_source(endpoint, _make_manager()))
+ next(iter(_source(endpoint, _make_manager()).items()))
assert params[0]["pageSize"] <= maximum
@@ -264,6 +273,121 @@ class TestRowNormalization:
assert rows[0]["createDate"] == datetime(2021, 1, 1, tzinfo=UTC)
+# Response list keys published in the vendor's OpenAPI spec. They differ per event stream, and a
+# wrong key silently yields an empty table.
+VENDOR_EVENT_DATA_KEYS: dict[str, str] = {
+ "page_view_events": "results",
+ "session_events": "sessionInitializedEvents",
+ "engagement_view_events": "results",
+ "feature_match_events": "featureMatchEvents",
+}
+
+
+NOW = datetime(2021, 1, 2, tzinfo=UTC)
+NOW_MS = 1609545600000
+DAY_MS = 24 * 60 * 60 * 1000
+# The vendor rejects an events request whose date range exceeds 190 days.
+VENDOR_MAX_EVENT_RANGE_MS = 190 * DAY_MS
+
+
+def _event_windows_requested(params: list[dict[str, Any]]) -> list[tuple[int, int]]:
+ windows = []
+ for request_params in params:
+ lower, upper = request_params["filter"].split(";")
+ assert lower.startswith("date>=") and upper.startswith("date<")
+ windows.append((int(lower.removeprefix("date>=")), int(upper.removeprefix("date<"))))
+ return windows
+
+
+class TestEventStreams:
+ @pytest.fixture(autouse=True)
+ def _frozen_now(self) -> Iterator[None]:
+ with time_machine.travel(NOW, tick=False):
+ yield
+
+ @parameterized.expand(sorted(VENDOR_EVENT_DATA_KEYS.items()))
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_rows_are_read_from_vendor_key_with_date_converted(self, endpoint: str, data_key: str, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response(data_key, [{"eventId": "e1", "date": 1609459200000}], scrollId=None)])
+
+ rows = _rows(_source(endpoint, _make_manager(), db_incremental_field_last_value=NOW - timedelta(days=1)))
+
+ assert rows == [{"eventId": "e1", "date": datetime(2021, 1, 1, tzinfo=UTC)}]
+
+ @parameterized.expand(
+ [
+ ("incremental_recent_watermark", datetime(2021, 1, 1, tzinfo=UTC), 1609459200000),
+ ("incremental_watermark_older_than_max_range", datetime(2019, 6, 1, tzinfo=UTC), 1559347200000),
+ ("full_refresh_backfills_history", None, NOW_MS - 730 * DAY_MS),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_requests_bounded_windows_covering_watermark_to_now(
+ self, _name: str, last_value: Any, expected_start_ms: int, MockSession
+ ) -> None:
+ session = MockSession.return_value
+ session.headers = {}
+ params: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ params.append(dict(request.params or {}))
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = lambda *_args, **_kwargs: _response("results", [], scrollId=None)
+
+ _rows(_source("page_view_events", _make_manager(), db_incremental_field_last_value=last_value))
+
+ windows = _event_windows_requested(params)
+ assert all(p["sort"] == "date" for p in params)
+ assert windows[0][0] == expected_start_ms
+ assert windows[-1][1] == NOW_MS
+ assert all(lower < upper <= lower + VENDOR_MAX_EVENT_RANGE_MS for lower, upper in windows)
+ assert all(prev[1] == nxt[0] for prev, nxt in zip(windows, windows[1:]))
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_mid_window_and_checkpoints_the_next_window(self, MockSession, monkeypatch) -> None:
+ monkeypatch.setattr(GAINSIGHT_PX_ENDPOINTS["session_events"], "page_size", 1)
+ window_start = NOW_MS - 200 * DAY_MS
+ session = MockSession.return_value
+ params = _wire(
+ session,
+ [
+ _response("sessionInitializedEvents", [], scrollId=None),
+ _response("sessionInitializedEvents", [], scrollId=None),
+ ],
+ )
+
+ manager = _make_manager(GainsightPxResumeConfig(scroll_id="saved-cursor", window_start=window_start))
+ _rows(_source("session_events", manager, db_incremental_field_last_value=datetime(2019, 1, 1, tzinfo=UTC)))
+
+ assert params[0]["scrollId"] == "saved-cursor"
+ assert _event_windows_requested(params)[0][0] == window_start
+ assert "scrollId" not in params[1]
+ manager.save_state.assert_called_once_with(GainsightPxResumeConfig(window_start=window_start + 180 * DAY_MS))
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_entity_endpoints_send_no_event_filter_or_sort(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_response("users", [], scrollId=None)])
+
+ _rows(_source("users", _make_manager(), db_incremental_field_last_value=datetime(2021, 1, 1, tzinfo=UTC)))
+
+ assert params[0] == {"pageSize": 1000}
+
+ @parameterized.expand(
+ [
+ ("aware_datetime", datetime(2021, 1, 1, 1, tzinfo=UTC), 1609462800000),
+ ("naive_datetime_is_utc", datetime(2021, 1, 1, 1), 1609462800000),
+ ("epoch_millis", 1609462800000, 1609462800000),
+ ("iso_string", "2021-01-01T01:00:00+00:00", 1609462800000),
+ ]
+ )
+ def test_watermark_to_epoch_millis(self, _name: str, value: Any, expected: int) -> None:
+ assert _to_epoch_millis(value) == expected
+
+
class TestRetries:
@mock.patch("tenacity.nap.time.sleep")
@mock.patch(CLIENT_SESSION_PATCH)
@@ -330,6 +454,7 @@ class TestSourceResponse:
("engagements", ["id"], None),
("articles", ["id"], "createdDate"),
("kc_bots", ["id"], "createdDate"),
+ ("session_events", ["eventId"], "date"),
]
)
@mock.patch(CLIENT_SESSION_PATCH)
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.py
index d74116883224..7497ef8cc409 100644
--- 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.py
@@ -25,13 +25,16 @@ class TestGainsightPxSource:
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):
+ @pytest.mark.parametrize(
+ "endpoint, incremental",
+ [(endpoint, endpoint.endswith("_events")) for endpoint in ENDPOINTS],
+ )
+ def test_only_event_streams_support_incremental(self, endpoint, incremental):
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
+ # Only the `/events/*` streams have a server-side date filter. Advertising incremental on an
+ # entity endpoint would silently corrupt the cursor.
+ assert schema.supports_incremental is incremental
+ assert schema.supports_append is incremental
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
def test_every_endpoint_advertises_a_primary_key(self, endpoint):