: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(warehouse): sync Gong call participants and CRM associations (#71046)
Simon Fisher3b9197e9f68d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gong/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gong/canonical_descriptions.pyindex 823843a0ac1c..5dbfc5fd25b9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gong/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gong/canonical_descriptions.py@@ -28,6 +28,26 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"scheduled": "Scheduled start time of the call, if applicable.",},},+ "calls_extensive": {+ "description": "A recorded Gong call enriched with its participants (`parties`) and CRM associations (`context`), sourced from the /v2/calls/extensive endpoint.",+ "docs_url": "https://gong.app.gong.io/settings/api/documentation#post-/v2/calls/extensive",+ "columns": {+ "id": "Unique identifier for the call.",+ "title": "Title of the call.",+ "url": "URL of the call within the Gong web app.",+ "started": "Time at which the call started (ISO 8601).",+ "duration": "Duration of the call in seconds.",+ "direction": "Direction of the call (Inbound, Outbound, Conference, or Unknown).",+ "scope": "Whether the call was internal or external.",+ "media": "Media type of the call (Audio or Video).",+ "language": "Detected primary language of the call.",+ "workspaceId": "Identifier of the workspace the call belongs to.",+ "primaryUserId": "Identifier of the main Gong user (host) on the call.",+ "scheduled": "Scheduled start time of the call, if applicable.",+ "parties": "Participants on the call — each with name, email address, affiliation (Internal/External), and any Gong user or CRM linkage.",+ "context": "CRM associations for the call — linked objects (e.g. Salesforce/HubSpot Account, Opportunity, Contact) and their field values.",+ },+ },"users": {"description": "A Gong user (team member whose calls and activity are tracked).","docs_url": "https://gong.app.gong.io/settings/api/documentation#get-/v2/users",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gong/gong.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gong/gong.pyindex cc373cf4efd6..66e865679c64 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gong/gong.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gong/gong.py@@ -104,6 +104,44 @@ def _build_url(path: str, params: dict[str, Any]) -> str:return f"{GONG_BASE_URL}{path}?{urlencode(params)}"+def _extensive_body(window_start: datetime, window_end: datetime, cursor: Optional[str]) -> dict[str, Any]:+ """Request body for `POST /v2/calls/extensive`.++ `contentSelector.context = "Extended"` asks Gong to return each call's CRM associations+ (linked Salesforce/HubSpot objects and their fields); `exposedFields.parties = true` returns+ the participants (name, email address, affiliation). Neither is available from the basic+ `/v2/calls` list endpoint. The pagination cursor travels in the body, not the query string.+ """+ body: dict[str, Any] = {+ "filter": {+ "fromDateTime": _format_datetime(window_start),+ "toDateTime": _format_datetime(window_end),+ },+ "contentSelector": {+ "context": "Extended",+ "exposedFields": {"parties": True},+ },+ }+ if cursor:+ body["cursor"] = cursor+ return body+++def _flatten_extensive_call(call: dict[str, Any]) -> dict[str, Any]:+ """Lift the `metaData` block of an extensive call row to the top level.++ `/v2/calls/extensive` nests the core call fields under `metaData` and returns `parties`+ and CRM `context` as siblings. Flattening `metaData` up keeps `id` and `started` available+ at the top level for primary-key merge and datetime partitioning, while preserving the+ enrichment as nested `parties`/`context` columns.+ """+ meta = call.get("metaData") or {}+ flattened = dict(meta)+ flattened["parties"] = call.get("parties")+ flattened["context"] = call.get("context")+ return flattened++def get_rows(access_key: str,access_key_secret: str,@@ -122,8 +160,14 @@ def get_rows(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)+ def fetch_page(url: str, json_body: Optional[dict[str, Any]] = None) -> dict[str, Any]:+ session = make_tracked_session(capture=config.capture_http_samples)+ # Extensive endpoints POST their filter/pagination in a JSON body; list endpoints GET.+ # `requests` sets `Content-Type: application/json` automatically for the `json=` kwarg.+ if json_body is not None:+ response = session.post(url, headers=headers, json=json_body, timeout=60)+ else:+ response = 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}")@@ -203,16 +247,23 @@ def _iter_windowed_rows(cursor: str | None = Nonewhile 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))+ if config.uses_extensive:+ data = fetch_page(+ _build_url(config.path, {}),+ json_body=_extensive_body(window_start, window_end, cursor),+ )+ rows = [_flatten_extensive_call(row) for row in data.get(config.response_key, [])]+ else:+ 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, [])- rows = data.get(config.response_key, [])if rows:yield rowsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gong/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gong/settings.pyindex e7e0519c1c5d..8a6e9609d856 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gong/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gong/settings.py@@ -19,6 +19,15 @@ class GongEndpointConfig:# `/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+ # `/v2/calls/extensive` is a POST endpoint whose filter, content selector, and pagination+ # cursor live in a JSON body, and whose rows wrap the call fields in a `metaData` object+ # alongside `parties` (participants) and CRM `context`. Requires the broader+ # `api:calls:read:extensive` scope.+ uses_extensive: bool = False+ # Whether responses from this endpoint may be sampled into HTTP troubleshooting storage.+ # Disabled for endpoints whose bodies carry participant names and free-form CRM field values+ # that the name-based scrubbers can't recognise; requests stay metered and logged.+ capture_http_samples: bool = TrueGONG_ENDPOINTS: dict[str, GongEndpointConfig] = {@@ -39,6 +48,29 @@ GONG_ENDPOINTS: dict[str, GongEndpointConfig] = {},],),+ # Same call universe as `calls`, but sourced from `POST /v2/calls/extensive` so each row+ # additionally carries `parties` (participant name/email/affiliation) and CRM `context`+ # (linked Salesforce/HubSpot objects and fields) — neither of which the basic `/v2/calls`+ # list can return. Kept as a separate table so enabling it never changes the `calls` schema.+ "calls_extensive": GongEndpointConfig(+ name="calls_extensive",+ path="/v2/calls/extensive",+ response_key="calls",+ primary_key="id",+ partition_key="started",+ supports_incremental=True,+ uses_date_window=True,+ uses_extensive=True,+ capture_http_samples=False,+ incremental_fields=[+ {+ "label": "started",+ "type": IncrementalFieldType.DateTime,+ "field": "started",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),"users": GongEndpointConfig(name="users",path="/v2/users",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gong/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gong/source.pyindex 0d3e843a4e51..74b5eb17ef40 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gong/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gong/source.py@@ -58,6 +58,9 @@ Grant the following read scopes so the connected endpoints can sync:- `api:users:read`- `api:settings:scorecards:read`- `api:workspaces:read`++To also sync the `calls_extensive` table (call participants and CRM associations), additionally grant:+- `api:calls:read:extensive`""",iconPath="/static/services/gong.png",docsUrl="https://posthog.com/docs/cdp/sources/gong",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gong/tests/test_gong.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gong/tests/test_gong.pyindex 4f5023e806ba..736ea40d08b4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gong/tests/test_gong.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gong/tests/test_gong.py@@ -42,16 +42,24 @@ class _FakeResponse:class _FakeSession:- """Records requested URLs and replays a queue of responses."""+ """Records requested URLs (and POST bodies) and replays a queue of responses."""def __init__(self, responses: list[_FakeResponse]):self._responses = list(responses)self.requested_urls: list[str] = []+ self.posted_bodies: list[dict | None] = []def get(self, url: str, headers: dict | None = None, timeout: int | None = None) -> _FakeResponse:self.requested_urls.append(url)return self._responses.pop(0)+ def post(+ self, url: str, headers: dict | None = None, json: dict | None = None, timeout: int | None = None+ ) -> _FakeResponse:+ self.requested_urls.append(url)+ self.posted_bodies.append(json)+ return self._responses.pop(0)+class _FakeResumableManager(ResumableSourceManager[GongResumeConfig]):"""In-memory stand-in for the Redis-backed manager (no `super().__init__`)."""@@ -336,4 +344,128 @@ class TestGongSource:assert response.partition_mode is Nonedef test_every_endpoint_has_a_config(self) -> None:- assert set(GONG_ENDPOINTS) == {"calls", "users", "scorecards", "workspaces"}+ assert set(GONG_ENDPOINTS) == {"calls", "calls_extensive", "users", "scorecards", "workspaces"}+++class TestExtensiveCalls:+ def test_posts_extensive_body_and_flattens_metadata(self) -> None:+ last_value = datetime.now(UTC) - timedelta(days=5)+ session = _FakeSession(+ [+ _FakeResponse(+ json_data={+ "calls": [+ {+ "metaData": {"id": "c1", "title": "Discovery", "started": "2026-03-01T00:00:00Z"},+ "parties": [{"emailAddress": "[email protected]", "affiliation": "External"}],+ "context": [{"system": "Salesforce", "objects": [{"objectType": "Account"}]}],+ }+ ]+ }+ )+ ]+ )+ manager = _FakeResumableManager()++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gong.gong.make_tracked_session",+ return_value=session,+ ):+ batches = list(+ get_rows(+ "key",+ "secret",+ "calls_extensive",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=last_value,+ )+ )++ # metaData is lifted to the top level; parties and CRM context ride along as columns.+ assert batches == [+ [+ {+ "id": "c1",+ "title": "Discovery",+ "started": "2026-03-01T00:00:00Z",+ "parties": [{"emailAddress": "[email protected]", "affiliation": "External"}],+ "context": [{"system": "Salesforce", "objects": [{"objectType": "Account"}]}],+ }+ ]+ ]+ # A single POST to the extensive endpoint with no query string.+ assert session.requested_urls == [f"{GONG_BASE_URL}/v2/calls/extensive"]+ body = session.posted_bodies[0]+ assert body is not None+ assert body["contentSelector"] == {"context": "Extended", "exposedFields": {"parties": True}}+ assert body["filter"]["fromDateTime"] == _format_datetime(last_value)+ assert "cursor" not in body++ def test_cursor_travels_in_body(self) -> None:+ last_value = datetime.now(UTC) - timedelta(days=5)+ session = _FakeSession(+ [+ _FakeResponse(json_data={"calls": [{"metaData": {"id": "c1"}}], "records": {"cursor": "page2"}}),+ _FakeResponse(json_data={"calls": [{"metaData": {"id": "c2"}}]}),+ ]+ )+ manager = _FakeResumableManager()++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gong.gong.make_tracked_session",+ return_value=session,+ ):+ batches = list(+ get_rows(+ "key",+ "secret",+ "calls_extensive",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=last_value,+ )+ )++ assert batches == [+ [{"id": "c1", "parties": None, "context": None}],+ [{"id": "c2", "parties": None, "context": None}],+ ]+ # The cursor is sent in the second request's body, never as a query param.+ second_body = session.posted_bodies[1]+ assert second_body is not None+ assert second_body["cursor"] == "page2"+ assert all("?" not in url for url in session.requested_urls)++ def test_response_body_capture_disabled_for_extensive_only(self) -> None:+ # Extensive responses carry participant names and free-form CRM fields, so they must be+ # excluded from HTTP sample capture; basic list endpoints stay captured for troubleshooting.+ last_value = datetime.now(UTC) - timedelta(days=5)++ extensive_session = _FakeSession([_FakeResponse(json_data={"calls": [{"metaData": {"id": "c1"}}]})])+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gong.gong.make_tracked_session",+ return_value=extensive_session,+ ) as extensive_factory:+ list(+ get_rows(+ "key",+ "secret",+ "calls_extensive",+ mock.MagicMock(),+ _FakeResumableManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=last_value,+ )+ )+ assert extensive_factory.call_args.kwargs["capture"] is False++ users_session = _FakeSession([_FakeResponse(json_data={"users": [{"id": "u1"}]})])+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gong.gong.make_tracked_session",+ return_value=users_session,+ ) as users_factory:+ list(get_rows("key", "secret", "users", mock.MagicMock(), _FakeResumableManager()))+ assert users_factory.call_args.kwargs["capture"] is True