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(warehouse): add gong transcripts table (#87324)

Daniel RC46e75a6afe04
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.py
index 5dbfc5fd25b9..583817a9b525 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
@@ -48,6 +48,15 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"context": "CRM associations for the call — linked objects (e.g. Salesforce/HubSpot Account, Opportunity, Contact) and their field values.",
},
},
+ "transcripts": {
+ "description": "The transcript of a recorded Gong call — what each speaker said, grouped into monologues and sentences.",
+ "docs_url": "https://gong.app.gong.io/settings/api/documentation#post-/v2/calls/transcript",
+ "columns": {
+ "callId": "Identifier of the call this transcript belongs to. Joins to `calls.id`.",
+ "started": "Time at which the call started (ISO 8601), taken from the call this transcript belongs to.",
+ "transcript": "The transcript itself — a list of monologues, each with the `speakerId` who spoke, the `topic` under discussion, and the `sentences` said (`text` plus `start` and `end` offsets in milliseconds from the beginning of the call).",
+ },
+ },
"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.py
index a2d3ba7d5143..de27930b005d 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
@@ -1,5 +1,4 @@
import base64
-import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
@@ -10,6 +9,8 @@ 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.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.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -33,10 +34,10 @@ class GongRetryableError(Exception):
pass
+@frozen
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
+ # ISO-8601 start of the next date window to fetch. Only the windowed, call-date-filtered
+ # endpoints persist 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
@@ -244,37 +245,135 @@ def _iter_windowed_rows(
while window_start < end:
window_end = min(window_start + timedelta(days=MAX_WINDOW_DAYS), end)
- cursor: str | None = None
-
- while True:
- 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, [])
-
- if rows:
- yield rows
-
- cursor = data.get("records", {}).get("cursor")
- if not cursor:
- break
+
+ if config.uses_call_id_batches:
+ yield from _iter_transcript_rows(config, fetch_page, window_start, window_end)
+ else:
+ yield from _iter_call_rows(config, fetch_page, window_start, window_end)
window_start = window_end
resumable_source_manager.save_state(GongResumeConfig(window_start=_format_datetime(window_start)))
+def _iter_call_rows(
+ config: GongEndpointConfig, fetch_page, window_start: datetime, window_end: datetime
+) -> Iterator[Any]:
+ """Cursor-paginate one date window of `/v2/calls`, or of its extensive POST form."""
+ cursor: str | None = None
+
+ while True:
+ 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, [])
+
+ if rows:
+ yield rows
+
+ cursor = data.get("records", {}).get("cursor")
+ if not cursor:
+ break
+
+
+def _iter_transcript_rows(
+ config: GongEndpointConfig, fetch_page, window_start: datetime, window_end: datetime
+) -> Iterator[Any]:
+ """Yield one date window of transcripts, each stamped with the start time of its call.
+
+ Walks the `/v2/calls` list for the window and asks for the transcripts of one page of call ids
+ at a time. That keeps the `callIds` filter bounded to a page, and gives every transcript the
+ `started` of the call it belongs to — `POST /v2/calls/transcript` returns no date of its own.
+ """
+ calls_config = GONG_ENDPOINTS["calls"]
+ 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
+
+ calls_page = fetch_page(_build_url(calls_config.path, params))
+
+ started_by_call_id = _call_start_times(calls_page.get(calls_config.response_key, []))
+ if started_by_call_id:
+ yield from _iter_transcripts_for_calls(config, fetch_page, window_start, window_end, started_by_call_id)
+
+ cursor = calls_page.get("records", {}).get("cursor")
+ if not cursor:
+ break
+
+
+def _call_start_times(calls: list[dict[str, Any]]) -> dict[str, Any]:
+ """Map each call's id to its start time, refusing a call that is missing either.
+
+ Both stamp the transcript rows that follow: the id is the primary key merge runs on, and
+ the start time is what the table partitions by and syncs incrementally on. A row missing
+ either is unmergeable and invisible to the watermark, so stop rather than write it.
+ """
+ start_times: dict[str, Any] = {}
+ for call in calls:
+ call_id, started = call.get("id"), call.get("started")
+ if not call_id or not started:
+ raise ValueError(f"Gong returned a call with no id or no start time (id={call_id!r})")
+ start_times[call_id] = started
+ return start_times
+
+
+def _stamp_transcript(transcript: dict[str, Any], started_by_call_id: dict[str, Any]) -> dict[str, Any]:
+ """Copy a transcript with the start time of the call it belongs to attached."""
+ call_id: Any = transcript.get("callId")
+ started = started_by_call_id.get(call_id)
+ if started is None:
+ raise ValueError(f"Gong returned a transcript for a call that was not asked for (callId={call_id!r})")
+ return {**transcript, "started": started}
+
+
+def _iter_transcripts_for_calls(
+ config: GongEndpointConfig,
+ fetch_page,
+ window_start: datetime,
+ window_end: datetime,
+ started_by_call_id: dict[str, Any],
+) -> Iterator[Any]:
+ cursor: str | None = None
+
+ while True:
+ body: dict[str, Any] = {
+ "filter": {
+ "fromDateTime": _format_datetime(window_start),
+ "toDateTime": _format_datetime(window_end),
+ "callIds": list(started_by_call_id),
+ }
+ }
+ if cursor:
+ body["cursor"] = cursor
+
+ data = fetch_page(_build_url(config.path, {}), json_body=body)
+
+ rows = [_stamp_transcript(row, started_by_call_id) for row in data.get(config.response_key, [])]
+ if rows:
+ yield rows
+
+ cursor = data.get("records", {}).get("cursor")
+ if not cursor:
+ break
+
+
def gong_source(
access_key: str,
access_key_secret: str,
@@ -305,4 +404,5 @@ def gong_source(
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,
+ chunk_size=config.chunk_size,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gong/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gong/settings.py
index 8a6e9609d856..9a567b231b78 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
@@ -1,10 +1,12 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@frozen
class GongEndpointConfig:
name: str
path: str
@@ -24,10 +26,22 @@ class GongEndpointConfig:
# alongside `parties` (participants) and CRM `context`. Requires the broader
# `api:calls:read:extensive` scope.
uses_extensive: bool = False
+ # `POST /v2/calls/transcript` answers with `callId` and `transcript` and nothing else. Endpoints
+ # that set this are driven off the `/v2/calls` list for the same window instead: each page of
+ # calls supplies the `callIds` filter for one transcript request, and the call's `started`
+ # stamps the rows that come back.
+ uses_call_id_batches: 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.
+ # Disabled for endpoints whose bodies carry participant names, free-form CRM field values, or
+ # verbatim conversation text that the name-based scrubbers can't recognise; requests stay
+ # metered and logged.
capture_http_samples: bool = True
+ # Trailing window each incremental run re-reads, for endpoints whose rows can appear well after
+ # the timestamp they sort by. None leaves the schema on the platform default.
+ default_incremental_lookback_seconds: Optional[int] = None
+ # Rows-per-chunk override for endpoints whose rows are whole documents. None keeps the
+ # pipeline's default.
+ chunk_size: Optional[int] = None
GONG_ENDPOINTS: dict[str, GongEndpointConfig] = {
@@ -71,6 +85,35 @@ GONG_ENDPOINTS: dict[str, GongEndpointConfig] = {
},
],
),
+ # Transcript text for the same calls, from `POST /v2/calls/transcript`, which returns only
+ # `callId` and `transcript`. Each row is stamped with the `started` of the call it belongs to,
+ # read from the `/v2/calls` page that drove the request — without it a transcript carries no
+ # date to sync incrementally on, partition by, or filter a query with.
+ # Requires the `api:calls:read:transcript` scope on top of `api:calls:read:basic`.
+ "transcripts": GongEndpointConfig(
+ name="transcripts",
+ path="/v2/calls/transcript",
+ response_key="callTranscripts",
+ primary_key="callId",
+ partition_key="started",
+ supports_incremental=True,
+ uses_date_window=True,
+ uses_call_id_batches=True,
+ capture_http_samples=False,
+ # Gong transcribes asynchronously, so a call synced before its transcript finished
+ # processing would otherwise sit below the watermark forever. Re-read the last week.
+ default_incremental_lookback_seconds=7 * 24 * 60 * 60,
+ # A row is a whole call transcript, so flush far fewer of them per Arrow table.
+ chunk_size=500,
+ 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.py
index dadc567e7b04..7c21260605be 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:
To also sync the `calls_extensive` table (call participants and CRM associations), additionally grant:
- `api:calls:read:extensive`
+
+To also sync the `transcripts` table (what was said on each call), additionally grant:
+- `api:calls:read:transcript`
""",
iconPath="/static/services/gong.png",
docsUrl="https://posthog.com/docs/cdp/sources/gong",
@@ -106,6 +109,7 @@ To also sync the `calls_extensive` table (call participants and CRM associations
supports_incremental=endpoint_config.supports_incremental,
supports_append=endpoint_config.supports_incremental,
incremental_fields=endpoint_config.incremental_fields,
+ default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,
description="Only syncs the last 365 days on initial sync"
if endpoint_config.uses_date_window
else None,
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.py
index 736ea40d08b4..f2f21567f5fa 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
@@ -323,6 +323,7 @@ class TestGongSource:
@parameterized.expand(
[
("calls", "id", "started", "asc"),
+ ("transcripts", "callId", "started", "asc"),
("users", "id", "created", "asc"),
("scorecards", "scorecardId", "created", "asc"),
("workspaces", "id", None, "asc"),
@@ -344,7 +345,14 @@ class TestGongSource:
assert response.partition_mode is None
def test_every_endpoint_has_a_config(self) -> None:
- assert set(GONG_ENDPOINTS) == {"calls", "calls_extensive", "users", "scorecards", "workspaces"}
+ assert set(GONG_ENDPOINTS) == {
+ "calls",
+ "calls_extensive",
+ "transcripts",
+ "users",
+ "scorecards",
+ "workspaces",
+ }
class TestExtensiveCalls:
@@ -439,33 +447,128 @@ class TestExtensiveCalls:
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)
+ @parameterized.expand(
+ [
+ # Extensive responses carry participant names and free-form CRM fields, and transcript
+ # responses carry verbatim conversation text, so neither may reach HTTP sample capture.
+ # Basic list endpoints stay captured for troubleshooting.
+ ("calls_extensive", [{"calls": [{"metaData": {"id": "c1"}}]}], False),
+ (
+ "transcripts",
+ [{"calls": [{"id": "c1", "started": "2026-03-01T00:00:00Z"}]}, {"callTranscripts": [{"callId": "c1"}]}],
+ False,
+ ),
+ ("users", [{"users": [{"id": "u1"}]}], True),
+ ]
+ )
+ def test_response_body_capture_per_endpoint(
+ self, endpoint: str, payloads: list[dict], expected_capture: bool
+ ) -> None:
+ session = _FakeSession([_FakeResponse(json_data=payload) for payload in payloads])
- 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:
+ return_value=session,
+ ) as session_factory:
list(
get_rows(
"key",
"secret",
- "calls_extensive",
+ endpoint,
+ mock.MagicMock(),
+ _FakeResumableManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime.now(UTC) - timedelta(days=5),
+ )
+ )
+
+ assert session_factory.call_args.kwargs["capture"] is expected_capture
+
+
+class TestTranscripts:
+ def test_drives_from_calls_and_stamps_each_transcript_with_its_call_start(self) -> None:
+ last_value = datetime.now(UTC) - timedelta(days=5)
+ session = _FakeSession(
+ [
+ _FakeResponse(
+ json_data={
+ "calls": [{"id": "c1", "started": "2026-03-01T00:00:00Z"}],
+ "records": {"cursor": "calls-page2"},
+ }
+ ),
+ _FakeResponse(json_data={"callTranscripts": [{"callId": "c1", "transcript": [{"speakerId": "u1"}]}]}),
+ _FakeResponse(json_data={"calls": [{"id": "c2", "started": "2026-03-02T00:00:00Z"}]}),
+ _FakeResponse(json_data={"callTranscripts": [{"callId": "c2", "transcript": []}]}),
+ ]
+ )
+
+ 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",
+ "transcripts",
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"}]})])
+ # `started` comes from the call the transcript belongs to — the transcript response has no
+ # date of its own, so without it the table can't sync incrementally or partition.
+ assert batches == [
+ [{"callId": "c1", "transcript": [{"speakerId": "u1"}], "started": "2026-03-01T00:00:00Z"}],
+ [{"callId": "c2", "transcript": [], "started": "2026-03-02T00:00:00Z"}],
+ ]
+ # Every page of the calls walk drives its own transcript request, so a second page of calls
+ # isn't dropped.
+ assert f"fromDateTime={_format_datetime(last_value)}" in unquote(session.requested_urls[0])
+ assert session.requested_urls[1] == f"{GONG_BASE_URL}/v2/calls/transcript"
+ assert "cursor=calls-page2" in session.requested_urls[2]
+ assert session.requested_urls[3] == f"{GONG_BASE_URL}/v2/calls/transcript"
+ # Each request asks only for the ids on the page that drove it.
+ assert [body["filter"]["callIds"] for body in session.posted_bodies if body] == [["c1"], ["c2"]]
+
+ @parameterized.expand(
+ [
+ # A call with no start time leaves its transcript with nothing to partition or sync on.
+ ("call_without_start_time", [{"id": "c1"}], [{"callId": "c1"}]),
+ # A transcript for a call we never asked for has no start time to borrow either.
+ (
+ "transcript_for_unrequested_call",
+ [{"id": "c1", "started": "2026-03-01T00:00:00Z"}],
+ [{"callId": "other"}],
+ ),
+ ]
+ )
+ def test_unstampable_transcript_stops_the_sync(
+ self, _name: str, calls: list[dict], transcripts: list[dict]
+ ) -> None:
+ session = _FakeSession(
+ [
+ _FakeResponse(json_data={"calls": calls}),
+ _FakeResponse(json_data={"callTranscripts": transcripts}),
+ ]
+ )
+
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
+ return_value=session,
+ ):
+ rows = get_rows(
+ "key",
+ "secret",
+ "transcripts",
+ mock.MagicMock(),
+ _FakeResumableManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime.now(UTC) - timedelta(days=5),
+ )
+ # Writing the row with `started=None` would bury it in the fallback partition and keep
+ # it out of the watermark, so no later run would ever correct it.
+ with pytest.raises(ValueError):
+ list(rows)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gong/tests/test_gong_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gong/tests/test_gong_source.py
index 71bbd62aa2d5..87005153340c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gong/tests/test_gong_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gong/tests/test_gong_source.py
@@ -52,10 +52,15 @@ class TestGongSource:
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)
+ # Only the call-date-filtered endpoints expose a server-side timestamp filter.
+ for name in ("calls", "calls_extensive", "transcripts"):
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert any(f["field"] == "started" for f in schemas[name].incremental_fields)
+
+ # Gong transcribes asynchronously, so transcripts re-read a trailing week on every run
+ # rather than leaving a call that had no transcript yet stranded below the watermark.
+ assert schemas["transcripts"].default_incremental_lookback_seconds == 7 * 24 * 60 * 60
for name in ("users", "scorecards", "workspaces"):
assert schemas[name].supports_incremental is False