: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 gong import source (#61662)
Tom Owerse01c2e79d683
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex f6552478df97..4c540288af29 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -75,6 +75,7 @@ the row lists both.| eventbrite | HTTP | requests | ✅ || front | HTTP | requests | ✅ || github | HTTP | requests | ✅ |+| gong | HTTP | requests | ✅ || google_ads | gRPC | google-ads (googleads.client) | ✅ || google_sheets | HTTP (vendor SDK) | gspread | ✅ || granola | HTTP | requests | ✅ |@@ -193,7 +194,6 @@ doesn't conflict with concurrent PRs.- firebase- fullstory- gitlab-- gong- google_analytics- google_drive- helpscoutdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 688d540b8232..580c293ea77d 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -399,7 +399,8 @@ class GithubSourceConfig(config.Config):@config.configclass GongSourceConfig(config.Config):- pass+ access_key: str+ access_key_secret: str@config.configdiff --git a/posthog/temporal/data_imports/sources/gong/gong.py b/posthog/temporal/data_imports/sources/gong/gong.pynew file mode 100644index 000000000000..c643007a3157--- /dev/null+++ b/posthog/temporal/data_imports/sources/gong/gong.py@@ -0,0 +1,248 @@+import base64+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from dateutil import parser as dateutil_parser+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.gong.settings import GONG_ENDPOINTS, GongEndpointConfig++# Gong's API base URL. Workspace API keys (HTTP Basic) authenticate against this host regardless+# of the customer's data region, so it stays fixed (no user-supplied host -> no SSRF surface).+GONG_BASE_URL = "https://api.gong.io"++# `/v2/calls` requires `fromDateTime` and rejects ranges wider than 90 days per request.+MAX_WINDOW_DAYS = 90+# How far back the first sync of `calls` reaches when there is no incremental cursor yet.+# Bounded so an initial backfill doesn't exhaust Gong's aggressive daily rate limit.+DEFAULT_INITIAL_LOOKBACK_DAYS = 365+++class GongRetryableError(Exception):+ pass+++class GongResumeConfig:+ # ISO-8601 start of the next `calls` date window to fetch. Only the windowed `calls`+ # endpoint persists resume state; cursors are deliberately not cached (Gong expires+ # them quickly), so on resume we restart the in-progress window from scratch and let+ # primary-key merge semantics dedupe any re-yielded rows.+ window_start: Optional[str] = None+++def _format_datetime(value: datetime) -> str:+ """ISO-8601 with a `Z` suffix, which Gong accepts for `fromDateTime`/`toDateTime`."""+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%S") + "Z"+++def _to_datetime(value: Any) -> Optional[datetime]:+ """Coerce an incremental cursor value (datetime/date/ISO string) to an aware UTC datetime."""+ if value is None:+ return None+ if isinstance(value, datetime):+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ try:+ parsed = dateutil_parser.parse(str(value))+ except (ValueError, TypeError, OverflowError):+ return None+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)+++def _get_headers(access_key: str, access_key_secret: str) -> dict[str, str]:+ token = base64.b64encode(f"{access_key}:{access_key_secret}".encode()).decode()+ return {+ "Authorization": f"Basic {token}",+ "Accept": "application/json",+ }+++def validate_credentials(+ access_key: str, access_key_secret: str, schema_name: Optional[str] = None+) -> tuple[bool, str | None]:+ """Probe a cheap endpoint to confirm the key pair is genuine.++ 401 means the credentials are invalid. 403 means the credentials are valid but lack the+ scope for this particular resource - accepted at source-create (``schema_name is None``)+ because users may grant only the scopes they intend to sync.+ """+ url = f"{GONG_BASE_URL}/v2/workspaces"+ try:+ response = make_tracked_session().get(url, headers=_get_headers(access_key, access_key_secret), 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 Gong access key or access key secret"+ if response.status_code == 403:+ if schema_name is None:+ return True, None+ return False, "Your Gong credentials do not have permission to access this endpoint"++ return False, f"Gong API returned an unexpected status code: {response.status_code}"+++def _build_url(path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{GONG_BASE_URL}{path}"+ return f"{GONG_BASE_URL}{path}?{urlencode(params)}"+++def get_rows(+ access_key: str,+ access_key_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GongResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[Any]:+ config = GONG_ENDPOINTS[endpoint]+ headers = _get_headers(access_key, access_key_secret)++ @retry(+ retry=retry_if_exception_type((GongRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+ )+ def fetch_page(url: str) -> dict[str, Any]:+ response = make_tracked_session().get(url, headers=headers, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise GongRetryableError(f"Gong API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Gong API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()++ if config.uses_date_window:+ yield from _iter_windowed_rows(+ config,+ fetch_page,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ else:+ yield from _iter_cursor_rows(config, fetch_page)+++def _iter_cursor_rows(config: GongEndpointConfig, fetch_page) -> Iterator[Any]:+ """Cursor-paginate a list endpoint until ``records.cursor`` is absent.++ Endpoints with no pagination (e.g. workspaces) return no cursor, so the loop exits after+ the first page.+ """+ cursor: str | None = None+ while True:+ params: dict[str, Any] = {"cursor": cursor} if cursor else {}+ data = fetch_page(_build_url(config.path, params))++ rows = data.get(config.response_key, [])+ if rows:+ yield rows++ cursor = data.get("records", {}).get("cursor")+ if not cursor:+ break+++def _iter_windowed_rows(+ config: GongEndpointConfig,+ fetch_page,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GongResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[Any]:+ """Sync `/v2/calls` by iterating bounded date windows oldest-first, cursor-paginating each.++ State is saved after each completed window. Cursors are never persisted; on resume we+ restart the in-progress window from its start and let merge dedupe re-yielded rows.+ """+ end = datetime.now(UTC)++ last_value = _to_datetime(db_incremental_field_last_value) if should_use_incremental_field else None+ window_start = last_value or (end - timedelta(days=DEFAULT_INITIAL_LOOKBACK_DAYS))++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None and resume_config.window_start:+ resumed = _to_datetime(resume_config.window_start)+ if resumed is not None:+ logger.debug(f"Gong: resuming calls from window start {resume_config.window_start}")+ window_start = resumed++ while window_start < end:+ window_end = min(window_start + timedelta(days=MAX_WINDOW_DAYS), end)+ cursor: str | None = None++ while True:+ params: dict[str, Any] = {+ "fromDateTime": _format_datetime(window_start),+ "toDateTime": _format_datetime(window_end),+ }+ if cursor:+ params["cursor"] = cursor++ data = fetch_page(_build_url(config.path, params))++ rows = data.get(config.response_key, [])+ if rows:+ yield rows++ cursor = data.get("records", {}).get("cursor")+ if not cursor:+ break++ window_start = window_end+ resumable_source_manager.save_state(GongResumeConfig(window_start=_format_datetime(window_start)))+++def gong_source(+ access_key: str,+ access_key_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GongResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = GONG_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ access_key=access_key,+ access_key_secret=access_key_secret,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=[config.primary_key],+ # Windows are iterated oldest-first, so the cursor watermark advances correctly.+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/posthog/temporal/data_imports/sources/gong/settings.py b/posthog/temporal/data_imports/sources/gong/settings.pynew file mode 100644index 000000000000..918185b14379--- /dev/null+++ b/posthog/temporal/data_imports/sources/gong/settings.py@@ -0,0 +1,68 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class GongEndpointConfig:+ name: str+ path: str+ # Key under which the records array lives in the JSON response (e.g. "calls", "users").+ response_key: str+ primary_key: str+ # Stable datetime field to partition by (never `updated`/`lastModified`). None disables partitioning.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Only `True` when Gong exposes a genuine server-side timestamp filter for the endpoint.+ supports_incremental: bool = False+ # `/v2/calls` requires `fromDateTime` and caps each request to a 90-day range, so it is+ # synced by iterating bounded date windows rather than a single cursor scan.+ uses_date_window: bool = False+++GONG_ENDPOINTS: dict[str, GongEndpointConfig] = {+ "calls": GongEndpointConfig(+ name="calls",+ path="/v2/calls",+ response_key="calls",+ primary_key="id",+ partition_key="started",+ supports_incremental=True,+ uses_date_window=True,+ incremental_fields=[+ {+ "label": "started",+ "type": IncrementalFieldType.DateTime,+ "field": "started",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "users": GongEndpointConfig(+ name="users",+ path="/v2/users",+ response_key="users",+ primary_key="id",+ partition_key="created",+ ),+ "scorecards": GongEndpointConfig(+ name="scorecards",+ path="/v2/settings/scorecards",+ response_key="scorecards",+ primary_key="scorecardId",+ partition_key="created",+ ),+ "workspaces": GongEndpointConfig(+ name="workspaces",+ path="/v2/workspaces",+ response_key="workspaces",+ primary_key="id",+ ),+}++ENDPOINTS = tuple(GONG_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in GONG_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/gong/source.py b/posthog/temporal/data_imports/sources/gong/source.pyindex ced8703ea843..d030f7708ca9 100644--- a/posthog/temporal/data_imports/sources/gong/source.py+++ b/posthog/temporal/data_imports/sources/gong/source.py@@ -1,19 +1,32 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import GongSourceConfig+from posthog.temporal.data_imports.sources.gong.gong import (+ GONG_BASE_URL,+ GongResumeConfig,+ gong_source,+ validate_credentials as validate_gong_credentials,+)+from posthog.temporal.data_imports.sources.gong.settings import GONG_ENDPOINTSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class GongSource(SimpleSource[GongSourceConfig]):+class GongSource(ResumableSource[GongSourceConfig, GongResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GONG@@ -23,7 +36,96 @@ class GongSource(SimpleSource[GongSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.GONG,label="Gong",- iconPath="/static/services/gong.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Gong API credentials to pull your Gong data into the PostHog Data warehouse.++Create an **Access Key** and **Access Key Secret** in Gong under **Company Settings > Ecosystem > API**.++Grant the following read scopes so the connected endpoints can sync:+- `api:calls:read:basic`+- `api:users:read`+- `api:settings:scorecards:read`+- `api:workspaces:read`+""",+ iconPath="/static/services/gong.png",+ docsUrl="https://posthog.com/docs/cdp/sources/gong",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_key",+ label="Access key",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="Your Gong access key",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="access_key_secret",+ label="Access key secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Your Gong access key secret",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: GongSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_incremental,+ incremental_fields=endpoint_config.incremental_fields,+ description="Only syncs the last 365 days on initial sync"+ if endpoint_config.uses_date_window+ else None,+ )+ for endpoint, endpoint_config in GONG_ENDPOINTS.items()+ ]+ 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: GongSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_gong_credentials(config.access_key, config.access_key_secret, schema_name)++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ f"401 Client Error: Unauthorized for url: {GONG_BASE_URL}": "Your Gong access key or secret is invalid. Please generate new credentials and reconnect.",+ f"403 Client Error: Forbidden for url: {GONG_BASE_URL}": "Your Gong credentials do not have the required permissions. Please check the granted scopes and try again.",+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GongResumeConfig]:+ return ResumableSourceManager[GongResumeConfig](inputs, GongResumeConfig)++ def source_for_pipeline(+ self,+ config: GongSourceConfig,+ resumable_source_manager: ResumableSourceManager[GongResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return gong_source(+ access_key=config.access_key,+ access_key_secret=config.access_key_secret,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/posthog/temporal/data_imports/sources/gong/tests/test_gong.py b/posthog/temporal/data_imports/sources/gong/tests/test_gong.pynew file mode 100644index 000000000000..e7cefe057dda--- /dev/null+++ b/posthog/temporal/data_imports/sources/gong/tests/test_gong.py@@ -0,0 +1,275 @@+import base64+from datetime import UTC, date, datetime, timedelta+from typing import Any+from urllib.parse import unquote++from unittest import mock++from parameterized import parameterized++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.gong.gong import (+ GONG_BASE_URL,+ GongResumeConfig,+ _build_url,+ _format_datetime,+ _get_headers,+ _to_datetime,+ get_rows,+ gong_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.gong.settings import GONG_ENDPOINTS+++class _FakeResponse:+ def __init__(self, status_code: int = 200, json_data: dict | None = None, text: str = ""):+ self.status_code = status_code+ self._json_data = json_data or {}+ self.text = text++ @property+ def ok(self) -> bool:+ return self.status_code < 400++ def json(self) -> dict:+ return self._json_data++ def raise_for_status(self) -> None:+ if not self.ok:+ raise Exception(f"{self.status_code} Client Error for url: {GONG_BASE_URL}")+++class _FakeSession:+ """Records requested URLs and replays a queue of responses."""++ def __init__(self, responses: list[_FakeResponse]):+ self._responses = list(responses)+ self.requested_urls: list[str] = []++ def get(self, url: str, headers: dict | None = None, timeout: int | None = None) -> _FakeResponse:+ self.requested_urls.append(url)+ return self._responses.pop(0)+++class _FakeResumableManager(ResumableSourceManager[GongResumeConfig]):+ """In-memory stand-in for the Redis-backed manager (no `super().__init__`)."""++ def __init__(self, resume_state: GongResumeConfig | None = None):+ self._resume_state = resume_state+ self.saved_states: list[GongResumeConfig] = []++ def can_resume(self) -> bool:+ return self._resume_state is not None++ def load_state(self) -> GongResumeConfig | None:+ return self._resume_state++ def save_state(self, data: GongResumeConfig) -> None:+ self.saved_states.append(data)+++class TestFormatDatetime:+ @parameterized.expand(+ [+ ("utc_aware", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("naive_treated_as_utc", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ]+ )+ def test_format_datetime(self, _name: str, value: datetime, expected: str) -> None:+ assert _format_datetime(value) == expected++ def test_no_plus_zero_offset(self) -> None:+ assert "+00:00" not in _format_datetime(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))+++class TestToDatetime:+ @parameterized.expand(+ [+ ("none", None, None),+ ("aware_datetime", datetime(2026, 1, 1, tzinfo=UTC), datetime(2026, 1, 1, tzinfo=UTC)),+ ("naive_datetime", datetime(2026, 1, 1), datetime(2026, 1, 1, tzinfo=UTC)),+ ("date", date(2026, 1, 1), datetime(2026, 1, 1, tzinfo=UTC)),+ ("iso_string", "2026-01-01T00:00:00Z", datetime(2026, 1, 1, tzinfo=UTC)),+ ("garbage_string", "not-a-date", None),+ ]+ )+ def test_to_datetime(self, _name: str, value: Any, expected: datetime | None) -> None:+ assert _to_datetime(value) == expected+++class TestGetHeaders:+ def test_basic_auth_header(self) -> None:+ headers = _get_headers("my-key", "my-secret")+ expected_token = base64.b64encode(b"my-key:my-secret").decode()+ assert headers["Authorization"] == f"Basic {expected_token}"+ assert headers["Accept"] == "application/json"+++class TestBuildUrl:+ def test_without_params(self) -> None:+ assert _build_url("/v2/users", {}) == f"{GONG_BASE_URL}/v2/users"++ def test_with_params(self) -> None:+ url = _build_url("/v2/calls", {"cursor": "abc"})+ assert url == f"{GONG_BASE_URL}/v2/calls?cursor=abc"+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, None, True, None),+ ("unauthorized", 401, None, False, "Invalid Gong access key or access key secret"),+ ("forbidden_source_create", 403, None, True, None),+ (+ "forbidden_for_schema",+ 403,+ "calls",+ False,+ "Your Gong credentials do not have permission to access this endpoint",+ ),+ ]+ )+ def test_validate_credentials(+ self, _name: str, status_code: int, schema_name: str | None, expected_valid: bool, expected_message: str | None+ ) -> None:+ session = _FakeSession([_FakeResponse(status_code=status_code)])+ with mock.patch("posthog.temporal.data_imports.sources.gong.gong.make_tracked_session", return_value=session):+ is_valid, message = validate_credentials("key", "secret", schema_name)++ assert is_valid is expected_valid+ assert message == expected_message+ assert session.requested_urls == [f"{GONG_BASE_URL}/v2/workspaces"]+++class TestCursorPagination:+ def test_paginates_until_cursor_absent(self) -> None:+ responses = [+ _FakeResponse(json_data={"users": [{"id": "1"}], "records": {"cursor": "abc"}}),+ _FakeResponse(json_data={"users": [{"id": "2"}]}),+ ]+ session = _FakeSession(responses)+ manager = _FakeResumableManager()++ with mock.patch("posthog.temporal.data_imports.sources.gong.gong.make_tracked_session", return_value=session):+ batches = list(get_rows("key", "secret", "users", mock.MagicMock(), manager))++ assert batches == [[{"id": "1"}], [{"id": "2"}]]+ assert session.requested_urls == [+ f"{GONG_BASE_URL}/v2/users",+ f"{GONG_BASE_URL}/v2/users?cursor=abc",+ ]+ # Non-windowed endpoints do not persist resume state.+ assert manager.saved_states == []++ def test_single_page_without_records(self) -> None:+ session = _FakeSession([_FakeResponse(json_data={"workspaces": [{"id": "w1"}]})])+ manager = _FakeResumableManager()++ with mock.patch("posthog.temporal.data_imports.sources.gong.gong.make_tracked_session", return_value=session):+ batches = list(get_rows("key", "secret", "workspaces", mock.MagicMock(), manager))++ assert batches == [[{"id": "w1"}]]+ assert session.requested_urls == [f"{GONG_BASE_URL}/v2/workspaces"]+++class TestWindowedCalls:+ def test_single_window_incremental(self) -> None:+ last_value = datetime.now(UTC) - timedelta(days=5)+ session = _FakeSession([_FakeResponse(json_data={"calls": [{"id": "c1"}]})])+ manager = _FakeResumableManager()++ with mock.patch("posthog.temporal.data_imports.sources.gong.gong.make_tracked_session", return_value=session):+ batches = list(+ get_rows(+ "key",+ "secret",+ "calls",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=last_value,+ )+ )++ assert batches == [[{"id": "c1"}]]+ # Exactly one window (last_value is within the 90-day cap of now).+ assert len(session.requested_urls) == 1+ assert f"fromDateTime={_format_datetime(last_value)}" in unquote(session.requested_urls[0])+ # State saved once after the window completes.+ assert len(manager.saved_states) == 1++ def test_cursor_within_window(self) -> None:+ last_value = datetime.now(UTC) - timedelta(days=5)+ responses = [+ _FakeResponse(json_data={"calls": [{"id": "c1"}], "records": {"cursor": "page2"}}),+ _FakeResponse(json_data={"calls": [{"id": "c2"}]}),+ ]+ session = _FakeSession(responses)+ manager = _FakeResumableManager()++ with mock.patch("posthog.temporal.data_imports.sources.gong.gong.make_tracked_session", return_value=session):+ batches = list(+ get_rows(+ "key",+ "secret",+ "calls",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=last_value,+ )+ )++ assert batches == [[{"id": "c1"}], [{"id": "c2"}]]+ assert "cursor=page2" in session.requested_urls[1]++ def test_resume_uses_saved_window_start(self) -> None:+ last_value = datetime.now(UTC) - timedelta(days=80)+ resume_start = datetime.now(UTC) - timedelta(days=10)+ session = _FakeSession([_FakeResponse(json_data={"calls": [{"id": "c1"}]})])+ manager = _FakeResumableManager(resume_state=GongResumeConfig(window_start=_format_datetime(resume_start)))++ with mock.patch("posthog.temporal.data_imports.sources.gong.gong.make_tracked_session", return_value=session):+ list(+ get_rows(+ "key",+ "secret",+ "calls",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=last_value,+ )+ )++ # The first request starts from the resumed window, not the DB cursor value.+ assert f"fromDateTime={_format_datetime(resume_start)}" in unquote(session.requested_urls[0])+++class TestGongSource:+ @parameterized.expand(+ [+ ("calls", "id", "started", "asc"),+ ("users", "id", "created", "asc"),+ ("scorecards", "scorecardId", "created", "asc"),+ ("workspaces", "id", None, "asc"),+ ]+ )+ def test_source_response_shape(+ self, endpoint: str, primary_key: str, partition_key: str | None, sort_mode: str+ ) -> None:+ response = gong_source("key", "secret", endpoint, mock.MagicMock(), _FakeResumableManager())++ assert response.name == endpoint+ assert response.primary_keys == [primary_key]+ assert response.sort_mode == sort_mode+ if partition_key:+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None+ assert response.partition_mode is None++ def test_every_endpoint_has_a_config(self) -> None:+ assert set(GONG_ENDPOINTS) == {"calls", "users", "scorecards", "workspaces"}diff --git a/posthog/temporal/data_imports/sources/gong/tests/test_gong_source.py b/posthog/temporal/data_imports/sources/gong/tests/test_gong_source.pynew file mode 100644index 000000000000..f45398dd9946--- /dev/null+++ b/posthog/temporal/data_imports/sources/gong/tests/test_gong_source.py@@ -0,0 +1,154 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import GongSourceConfig+from posthog.temporal.data_imports.sources.gong.gong import GongResumeConfig+from posthog.temporal.data_imports.sources.gong.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.gong.source import GongSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestGongSource:+ def setup_method(self):+ self.source = GongSource()+ self.team_id = 123+ self.config = GongSourceConfig(access_key="key", access_key_secret="secret")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.GONG++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Gong"+ assert config.label == "Gong"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/gong.png"++ fields = config.fields+ assert len(fields) == 2++ access_key_field, secret_field = fields+ assert isinstance(access_key_field, SourceFieldInputConfig)+ assert access_key_field.name == "access_key"+ assert access_key_field.type == SourceFieldInputConfigType.TEXT+ assert access_key_field.required is True++ assert isinstance(secret_field, SourceFieldInputConfig)+ assert secret_field.name == "access_key_secret"+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_field.required is True+ assert secret_field.secret is True++ def test_get_schemas(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ def test_get_schemas_incremental_flags(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ # Only `calls` exposes a server-side timestamp filter.+ assert schemas["calls"].supports_incremental is True+ assert schemas["calls"].supports_append is True+ assert any(f["field"] == "started" for f in schemas["calls"].incremental_fields)++ for name in ("users", "scorecards", "workspaces"):+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["calls"])++ assert len(schemas) == 1+ assert schemas[0].name == "calls"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["nonexistent"])++ assert schemas == []++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, None), True, None),+ (+ (False, "Invalid Gong access key or access key secret"),+ False,+ "Invalid Gong access key or access key secret",+ ),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.gong.source.validate_gong_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ 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 == expected_message+ mock_validate.assert_called_once_with(self.config.access_key, self.config.access_key_secret, None)++ @pytest.mark.parametrize(+ "expected_key",+ [+ "401 Client Error: Unauthorized for url: https://api.gong.io",+ "403 Client Error: Forbidden for url: https://api.gong.io",+ ],+ )+ def test_non_retryable_errors_includes_gong_keys(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ @pytest.mark.parametrize(+ "other_vendor_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "403 Client Error: Forbidden for url: https://api.klaviyo.com/api/accounts",+ ],+ )+ def test_non_retryable_errors_does_not_match_other_vendors(self, other_vendor_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_vendor_error for key in non_retryable_errors)++ def test_get_resumable_source_manager(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is GongResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self):+ inputs = mock.MagicMock()+ inputs.schema_name = "calls"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = mock.MagicMock()++ with mock.patch("posthog.temporal.data_imports.sources.gong.source.gong_source") as mock_gong_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_gong_source.assert_called_once()+ kwargs = mock_gong_source.call_args.kwargs+ assert kwargs["access_key"] == "key"+ assert kwargs["access_key_secret"] == "secret"+ assert kwargs["endpoint"] == "calls"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ def test_source_for_pipeline_omits_last_value_on_full_refresh(self):+ inputs = mock.MagicMock()+ inputs.schema_name = "users"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ with mock.patch("posthog.temporal.data_imports.sources.gong.source.gong_source") as mock_gong_source:+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ kwargs = mock_gong_source.call_args.kwargs+ assert kwargs["db_incremental_field_last_value"] is None